asp.net core系列 52 Identity 其它關注點

一.登錄分析

在使用identity身份驗證登錄時,在login中調用的方法是:

  var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);

跟蹤查看源碼,源碼下載https://github.com/aspnet/AspNetCore/releases 這里有core源碼的不同版本,在vs 2017下只能加載2.2及以下的版本。
下面是登錄的大概步驟:
 (1) 檢查用戶名是否存在(UserManager.cs在Microsoft.AspNetCore.Identity.core源碼中)

var user = await UserManager.FindByNameAsync(userName);

(2) UserManager類來檢查用戶名和密碼是否存在

 UserManager.CheckPasswordAsync(user, password)

(3) 登錄,isPersistent是指瀏覽器關閉后登錄cookie是否應該保持,如果是true則永久保存cookie,如果為false則使用services.ConfigureApplicationCookie中options.ExpireTimeSpan 來重寫。SignInOrTwoFactorAsync(user, isPersistent)方法最終調用SignInAsync進行登錄。

public virtual async Task SignInAsync(TUser user, AuthenticationProperties authenticationProperties, string authenticationMethod = null)
        {
            var userPrincipal = await CreateUserPrincipalAsync(user);
            // Review: should we guard against CreateUserPrincipal returning null?
            if (authenticationMethod != null)
            {
                userPrincipal.Identities.First().AddClaim(new Claim(ClaimTypes.AuthenticationMethod, authenticationMethod));
            }
            await Context.SignInAsync(IdentityConstants.ApplicationScheme,
                userPrincipal,
                authenticationProperties ?? new AuthenticationProperties());
        }

AuthenticationProperties:用來存儲身份認證會話
IdentityConstants:是配置Identity系統(tǒng)使用的cookie中間件的所有選項, ApplicationScheme屬性是指:該方案運用于Identity應用程序的cookies(默認方案)。如下所示:

  private static readonly string CookiePrefix = "Identity";
          public static readonly string ApplicationScheme = CookiePrefix + ".Application"

登錄涉及到三個類ClaimsPrincipal(聲明當事人)、ClaimsIdentity(聲明標識)、Claim(聲明)。

Claim:是名稱值對,比如名稱ClaimType:身份證, 值ClaimValue:18位號碼。

ClaimsIdentity:一組Cliams 就構成了一個Identity標識。

ClaimsPrincipal:當事人可以持有多個ClaimsIdentity標識。

最后SignInAsync 創(chuàng)建一個加密的 cookie,并將其添加到當前響應。

二.注銷

若要注銷(退出登錄)當前用戶,然后刪除其 cookie,需要調用SignOutAsync 。

await HttpContext.SignOutAsync();    

三. Identity表管理

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容