1. 程式人生 > >ASP.NET CORE系列【四】基於Claim登錄授權

ASP.NET CORE系列【四】基於Claim登錄授權

amp account 技術 time 其他 cookie first arp 好的

介紹

關於什麽是Claim?

可以看看其他大神的文章:

http://www.cnblogs.com/jesse2013/p/aspnet-identity-claims-based-authentication-and-owin.html

http://www.cnblogs.com/savorboard/p/aspnetcore-identity.html

註:本人目前還是菜鳥初學階段,如有寫錯的地方,望各位大鳥 指出!

場景

用戶登錄是一個非常常見的應用場景 .net core的登錄方式跟以往有些不同,可以說是往好的方向發展,變得更容易擴展,更方便。

在上一章裏面,有過簡單的介紹,那麽這一章,我們來詳細看看。

配置

1.首先需要NuGet安裝一個包:Microsoft.AspNetCore.Authentication.Cookies

打開項目中的Startup.cs文件,找到ConfigureServices方法,我們通常在這個方法裏面做依賴註入的相關配置。

public void ConfigureServices(IServiceCollection services)
        {//增加Cookie中間件配置
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme 
= "MyCookieAuthenticationScheme"; options.DefaultChallengeScheme = "MyCookieAuthenticationScheme"; options.DefaultSignInScheme = "MyCookieAuthenticationScheme"; }) .AddCookie("MyCookieAuthenticationScheme", options => {
//options.AccessDeniedPath = "/Account/Forbidden"; options.LoginPath = "/Home/Login"; }); }

這裏的代碼意思是 添加授權,添加使用Cookie的方式,配置登錄頁面和沒有權限時的跳轉頁面。

2.再找到Configure方法,添加 app.UseAuthentication(),使用授權:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, EFCoreContext context)
        {
           
            app.UseAuthentication();
           
        }

3.創建一個新的 Controller,並添加登錄的方法:

 public async Task<IActionResult> Login([FromBody]  SysUser sysUser)
        {
                //使用ef獲取用戶
                var info = _context.SysUsers.Where(m => m.UserName == sysUser.UserName && m.PassWord == sysUser.PassWord).FirstOrDefault();
                if (info != null)
                {    
                    //創建一個身份認證
                    var claims = new List<Claim>() {
                    new Claim(ClaimTypes.Sid,info.Id.ToString()), //用戶ID
                    new Claim(ClaimTypes.Name,info.UserName)  //用戶名稱
                    }; 

                    var identity = new ClaimsIdentity(claims, "TestLogin");
                    var userPrincipal = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                        IsPersistent = false,
                        AllowRefresh = false
                    });
                    return Json(new
                    {
                        success = true
                    });
                }
                else
                {
                    return Json(new
                    {
                        success = false,
                        message = "賬戶名密碼錯誤!"
                    });
                }
        }

由以上代碼,我們來具體分析。

ASP.NET Core 的驗證模型是 claims-based authentication 。Claim 是對被驗證主體特征的一種表述,比如:登錄用戶名是xxx,email是xxx,其中的“登錄用戶名”,“email”就是ClaimType.

一組claims構成了一個identity,具有這些claims的identity就是 ClaimsIdentity

 var claims = new List<Claim>() {
                    new Claim(ClaimTypes.Sid,info.Id.ToString()), //用戶ID
                    new Claim(ClaimTypes.Name,info.UserName)  //用戶名稱
                    }; 

                    var identity = new ClaimsIdentity(claims, "Login");

  

ClaimsIdentity的持有者就是 ClaimsPrincipal

  var userPrincipal = new ClaimsPrincipal(identity);

一個ClaimsPrincipal可以持有多個ClaimsIdentity,就比如一個人既持有駕照,又持有護照.

var userPrincipal = new ClaimsPrincipal(identity);
                    await HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

理解了Claim, ClaimsIdentity, ClaimsPrincipal這三個概念,就能理解生成登錄Cookie為什麽要用之前的代碼。

要用Cookie代表一個通過驗證的主體,必須包含Claim, ClaimsIdentity, ClaimsPrincipal這三個信息,ClaimsPrincipal就是持有證件的人,ClaimsIdentity就是證件,"Login"就是證件類型(這裏假設是駕照),Claim就是駕照中的信息。

我們在需要驗證權限的Action上面加入[Authorize] 就可以了, 如果沒有登錄狀態,會跳轉到Login頁面, 如何配置跳轉,已經各種其他的配置,見Startup.cs文件、

 public IActionResult Index()
        {//取用戶信息
            var userId = User.FindFirst(ClaimTypes.Sid).Value;
            var userName = User.Identity.Name;
            return View();
        }

為什麽User.Identity.Name可以取到用戶名呢, 我們看看User的定義:

技術分享圖片

沒錯,他就是我們上面說的ClaimsPrincipal

此時,我掏出身份證(ClaimsIdentity),身份證上面有我的名稱 (claim)

4.退出登錄

public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("MyCookieAuthenticationScheme");
            return RedirectToAction("Index", "Home");
        }

 

ASP.NET CORE系列【四】基於Claim登錄授權