一.登錄分析
在使用identity身份驗(yàn)證登錄時(shí),在login中調(diào)用的方法是:
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類來(lái)檢查用戶名和密碼是否存在
UserManager.CheckPasswordAsync(user, password)
(3) 登錄,isPersistent是指瀏覽器關(guān)閉后登錄cookie是否應(yīng)該保持,如果是true則永久保存cookie,如果為false則使用services.ConfigureApplicationCookie中options.ExpireTimeSpan 來(lái)重寫(xiě)。SignInOrTwoFactorAsync(user, isPersistent)方法最終調(diào)用SignInAsync進(jìn)行登錄。
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:用來(lái)存儲(chǔ)身份認(rèn)證會(huì)話
IdentityConstants:是配置Identity系統(tǒng)使用的cookie中間件的所有選項(xiàng), ApplicationScheme屬性是指:該方案運(yùn)用于Identity應(yīng)用程序的cookies(默認(rèn)方案)。如下所示:
private static readonly string CookiePrefix = "Identity";
public static readonly string ApplicationScheme = CookiePrefix + ".Application"
登錄涉及到三個(gè)類ClaimsPrincipal(聲明當(dāng)事人)、ClaimsIdentity(聲明標(biāo)識(shí))、Claim(聲明)。
Claim:是名稱值對(duì),比如名稱ClaimType:身份證, 值ClaimValue:18位號(hào)碼。
ClaimsIdentity:一組Cliams 就構(gòu)成了一個(gè)Identity標(biāo)識(shí)。
ClaimsPrincipal:當(dāng)事人可以持有多個(gè)ClaimsIdentity標(biāo)識(shí)。
最后SignInAsync 創(chuàng)建一個(gè)加密的 cookie,并將其添加到當(dāng)前響應(yīng)。
二.注銷
若要注銷(退出登錄)當(dāng)前用戶,然后刪除其 cookie,需要調(diào)用SignOutAsync 。
await HttpContext.SignOutAsync();