IDS4 單點登錄與注冊登錄。


 
        

今天我們講解的是關於net core 中用IdentityServer4 做單點登錄和注冊登錄。

    1,我們需要新建一個net core 的項目,如下圖:

    

 

    

 

  2,我們需要新建一個登錄的控制器,封裝登錄的方法 (首頁視圖登錄和判斷邏輯最好分開),代碼如下:

     

  1.      [HttpGet]
  2.       public IActionResult Login(string returnUrl = null)
  3.         {
  4.             ViewData["returnUrl"] = returnUrl;
  5.             return View();
  6.         }
  7.         /// <summary>
  8.         /// 登錄post回發處理
  9.         /// </summary>
  10.         [HttpPost]
  11.         public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
  12.         {
  13.             ViewData["returnUrl"] = returnUrl;
  14.               Customers customers= _userDAL.Login(userName, password);
  15.             //UserDAL userDAL = new UserDAL();  //不予許實例化對象
  16.             if (customers != null)
  17.             {
  18.                 AuthenticationProperties props = new AuthenticationProperties
  19.                 {
  20.                     IsPersistent = true,
  21.                     ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1)),
  22.                 };
  23.                 //注意這里應該引用Microsoft.AspNetCore.Http這個下面的
  24.                 await HttpContext.SignInAsync("10000", userName, props);
  25.                 //HttpContext.SignOutAsync();
  26.                 if (returnUrl != null)
  27.                 {
  28.                     return Redirect(returnUrl);
  29.                     //return Redirect("http://localhost:44396/home/index");
  30.                 }
  31.                 return View();
  32.             }
  33.             else
  34.             {
  35.                 return Content("登錄失敗");
  36.             }
  37.         }

    前台代碼如下:

  1. <html>
  2. <head>
  3.     <meta name="viewport" content="width=device-width" />
  4.     <title>Login</title>
  5. </head>
  6. <body>
  7.     <div align="center">
  8.         <h1>.net58統一認證登錄中心</h1>
  9.         <form method="post" action="/Acount/Login">
  10.             用戶名:<input type="text" name="userName" /><br />
  11.             密  碼:<input type="password" name="password" />
  12.             <input type="hidden" name="returnUrl" value="@ViewData["returnUrl"]" /> <br />
  13.             <input type="submit" value="登錄" />
  14.         </form>
  15.     </div>
  16. </body>
  17. </html>

3,我們需要添加一個類,Config,在里面實現單點登錄的方法,當然也需要依賴注入identityServer4,代碼如下:

      

  1.  public class Config
  2.     {
  3.         //下載ids4的依賴:install-package IdentityServer4  -version 2.1.1
  4.         // scopes define the resources in your system
  5.         public static IEnumerable<IdentityResource> GetIdentityResources()
  6.         {
  7.             return new List<IdentityResource>
  8.             {
  9.                 new IdentityResources.OpenId(),
  10.                 new IdentityResources.Profile(),
  11.             };
  12.         }
  13.         // clients want to access resources (aka scopes)
  14.         public static IEnumerable<Client> GetClients()
  15.         {
  16.             return new List<Client>
  17.             {
  18.                 // OpenID Connect隱式流客戶端(MVC)
  19.                 new Client
  20.                 {
  21.                     ClientId = "net58.order",
  22.                     ClientName = "MVC Client",
  23.                     AllowedGrantTypes = GrantTypes.Implicit,//隱式方式
  24.                     RequireConsent=false,//如果不需要顯示否同意授權 頁面 這里就設置為false                      
  25.                     RedirectUris = { "http://localhost:60944/signin-oidc""http://localhost:33447/account/index" },//登錄成功后返回的客戶端地址
  26.                     //PostLogoutRedirectUris = { "http://localhost:60944/signout-callback-oidc" },//注銷登錄后返回的客戶端地址
  27.                     AllowedScopes =
  28.                     {
  29.                         IdentityServerConstants.StandardScopes.OpenId,
  30.                         IdentityServerConstants.StandardScopes.Profile
  31.                     }
  32.                 },
  33.                  new Client
  34.                 {
  35.                     ClientId = "net58.product",
  36.                     ClientName = "MVC Client",
  37.                     AllowedGrantTypes = GrantTypes.Implicit,//隱式方式
  38.                     RequireConsent=false,//如果不需要顯示否同意授權 頁面 這里就設置為false                      
  39.                     RedirectUris = { "http://localhost:61739/signin-oidc""http://localhost:33447/account/index" },//登錄成功后返回的客戶端地址
  40.                     //PostLogoutRedirectUris = { "http://localhost:61739/signout-callback-oidc" },//注銷登錄后返回的客戶端地址
  41.                     AllowedScopes =
  42.                     {
  43.                         IdentityServerConstants.StandardScopes.OpenId,
  44.                         IdentityServerConstants.StandardScopes.Profile
  45.                     }
  46.                 }
  47.             };
  48.         }
  49.     }

思路分析:我們可以NuGet包依賴注入ids4,后面的ClientId,ClientName,RedirectUris 就分別配置為其他兩個單點項目的Startup.cs服務里

  4,我們需要在登錄項目的Startup.cs服務里配置Ids4服務的相關文件,代碼如下:

  1.  public void ConfigureServices(IServiceCollection services)
  2.         {
  3.             //好像是歐盟聯盟協議的cookie,要注釋
  4.             //services.Configure<CookiePolicyOptions>(options =>
  5.             //{
  6.             //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  7.             //    options.CheckConsentNeeded = context => true;
  8.             //    options.MinimumSameSitePolicy = SameSiteMode.None;
  9.             //});
  10.             services.AddIdentityServer()//Ids4服務
  11.              .AddDeveloperSigningCredential()//添加開發人員簽名憑據
  12.              .AddInMemoryIdentityResources(Config.GetIdentityResources()) //添加內存apiresource
  13.              .AddInMemoryClients(Config.GetClients());//把配置文件的Client配置資源放到內存
  14.            
  15.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  16.         }
  17.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  18.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  19.         {
  20.             if (env.IsDevelopment())
  21.             {
  22.                 app.UseDeveloperExceptionPage();
  23.             }
  24.             else
  25.             {
  26.                 app.UseExceptionHandler("/Home/Error");
  27.             }
  28.             app.UseStaticFiles();
  29.             app.UseCookiePolicy();
  30.             //啟動ids4中間件
  31.             app.UseIdentityServer();
  32.             app.UseMvc(routes =>
  33.             {
  34.                 routes.MapRoute(
  35.                     name: "default",
  36.                     template"{controller=Home}/{action=Index}/{id?}");
  37.             });
  38.         }

  tip:初學者可以參考里面的配置,沒有的要加上哦。

 5,項目就需要在子項目進行配置了 (這里做功能測試,所以只建了兩個子項目,大型項目的話可以弄多個進行單點登錄的)

 這里,我們新建商品和價格,兩個子項目來進行單點登錄。

  1.  //下載ids4的依賴:install-package IdentityServer4  -version 2.1.1

 

Startup.cs服務里配置代碼如下圖:

  

  

       

  1.    app.UseStaticFiles();
  2.             app.UseCookiePolicy();
  3.             //身份驗證  批准; 授權
  4.             app.UseAuthentication();
  5.             //啟動session 中間件
  6.             app.UseSession();
  7.             app.UseMvc(routes =>
  8.             {
  9.                 routes.MapRoute(
  10.                     name: "default",
  11.                     template"{controller=Home}/{action=Index}/{id?}");
  12.             });

  在新建的控制器,只需要一個特寫權限,視圖的話就寫上登錄成功訪問就行了。

  

 

這個價格子項目配置好了之后,另外那個商品子項目的配置也一致。

下面我們就可以運行子項目,開始你訪問該控制器(UserCenter)下的index視圖,他會跳轉到登錄項目進行登錄

  登錄成功后就返回到當前的價格子項目,然后我們再運行商品子項目,會發現他就不需要登錄就可以訪問index視圖下的登錄成功訪問的話語。

 

tip:運行時,我們可以清楚看到登錄界面和登錄成功后的頁面的路由路徑是不一致的,所以就實現了單點登錄的效果。

 

 第二項內容就是:實現注銷登錄:(隨便一個子項目退出登錄,其他項目也就退出了登錄)

 1,在以上的基礎上,還是在登錄控制器封裝注銷登錄的方法,代碼如下:

    

  1. public class AccountController : Controller
  2.     {
  3. //依賴注入:做注銷登錄
  4.         private readonly IIdentityServerInteractionService _interaction;
  5.         public AccountController(IIdentityServerInteractionService interaction)
  6.         {
  7.             _interaction = interaction;
  8.           
  9.         }
  10.         //注銷登錄
  11.         [HttpGet]
  12.         public async Task<IActionResult> Logout(string logoutId)
  13.         {
  14.             var logout = await _interaction.GetLogoutContextAsync(logoutId);
  15.             await HttpContext.SignOutAsync();
  16.             //if (logout.PostLogoutRedirectUri != null)
  17.             //{
  18.             //    return Redirect(logout.PostLogoutRedirectUri); 
  19.             //}
  20.             //獲取客戶端點擊注銷登錄的地址
  21.             var refererUrl = Request.Headers["Referer"].ToString();
  22.             if (!string.IsNullOrWhiteSpace(refererUrl))
  23.             {
  24.                 return Redirect(refererUrl);
  25.             }
  26.             else
  27.             {
  28.                 //獲取配置的默認的注銷登錄后的跳轉地址
  29.                 if (logout.PostLogoutRedirectUri != null)
  30.                 {
  31.                     return Redirect(logout.PostLogoutRedirectUri);
  32.                 }
  33.             }
  34.             return View();
  35.         }

2,在價格子項目為例:在UserCenter控制器加一個視圖類:

   

  1. //退出登錄
  2. public IActionResult LoginOut()
  3.         {
  4.             return SignOut("Cookies""oidc");
  5.         }

3,最后一步,我們就在子項目隨便一個控制器運行,然后寫連接跳轉到退出登錄的控制器下的類訪問就可以實現退出,他就會返回該子項目

    且處於未登錄狀態,我們以另外一個商品項目啟動運行,訪問那個提示登錄成功訪問的視圖,發現需要重新登錄。

    效果完成后就達到單點注銷登錄啦。不容易呀,知識還是需要慢慢啃哦,加油。

隨筆轉自:https://www.tnblog.net/15985459135/article/details/3055


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM