一.登錄分析
在使用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();