.NET core3.1使用cookie進行身份認證

一個系統,用戶身份認證少不了,ASP.NET Core提供完整的解決方案Identity,用戶建立和維護登陸名;也提供能cookie和JwtBearer認證方案,固然你可使用第三方認證Oauth、openId。項目沒有采用先後端分離,是一個標準的mvc項目,因此本文采用系統提供的cookie認證 記錄一下簡單認證流程,(1)使用用戶帳號密碼進行登陸,驗證合法登陸(2)確認合法身份以後,會頒發一個認證票據(加密)會攜帶與該用戶相關的身份、權限以及其餘信息。(3)退出。ajax

主要會使用Microsoft.AspNetCore.Authentication.Abstractions包中 AuthenticationHttpContextExtensions類,它是基於HttpContext上公開身認證的擴展法:後端

方法 描述
SignInAsync 登陸用戶.用戶登陸成功後頒發一個證書(加密的用戶憑證,這個憑證放入Cookie中),用來標識用戶的身份
SignOutAsync 註銷退出.清除Cookie
GetTokenAsync 用來獲取 AuthenticationProperties 中保存的額外信息
ForbidAsync 通知用戶權限不足,若是是ajax請求返回403狀態碼,不是ajax請求跳轉指定的url
ChallengeAsync 通知用戶須要登陸。在默認實現類AuthenticationHandler中,返回401
AuthenticateAsync 驗證在 SignInAsync 中頒發的證書,並返回一個 AuthenticateResult 對象,表示用戶的身份。

登陸建立一個cookie認證

這裏涉及幾個對象:Claim聲明經常表明,認證用戶身份的元數據信息,好比手機號、郵箱、用戶名等等。ClaimsIdentity聲明主體,表明一個認證用戶的身份證,固然包含聲明的集合。ClaimsPrincipal身份證持有者。微信

流程:建立一個包含用戶信息的 cookie須要構造一個ClaimsPrincipal。將序列化用戶信息並將其存儲在中 cookie 。cookie

用必要的 Claim來構造一個ClaimsIdentity,而後調用 SignInAsync 來登陸用戶。session

public async Task<Result> UserLogin([FromForm] UserLoginInput input)
{
//登陸邏輯
var model = userService.UserLogin(input);

//1.建立cookie 保存用戶信息,使用claim。將序列化用戶信息並將其存儲在cookie
var claims = new List<Claim>()
{
new Claim(ClaimTypes.MobilePhone,model.Mobile),
new Claim(ClaimTypes.Name,model.UserName),
new Claim("Id",model.SysNo.ToString())
};

//2.建立聲明主題 指定認證方式 這裏使用cookie
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

//3.配置認證屬性 好比過時時間,是否持久化。。。。
var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed.

//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.

//IsPersistent = true,
//持久化 ,好比 登陸的時候 勾選記住我 複選框

//IssuedUtc = <DateTimeOffset>,
//絕對cookie過時

//RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
};

//4.登陸
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

return Result.ResponseSuccess();
}

SignInAsync 建立一個加密的 cookie ,並將其添加到當前響應中。mvc

退出

退出很簡單,主要用戶清除cookieapp

HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

獲取認證信息

登陸以後,咱們一般會獲取一些聲明中的信息,可使用 HttpContext.User 將會返回一個ClaimsPrincipal對象前後端分離

ClaimsPrincipal principal = HttpContext.User;
if (null != principal)
{
foreach (Claim claim in principal.Claims)
{
var ii = "CLAIM TYPE: " + claim.Type + "; CLAIM VALUE: " + claim.Value + "</br>";
}

}

統一處理獲取到的信息,賦值UserViewModel實例CurrentLoginUserasync

public class BaseController : Controller
{
public UserViewModel CurrentLoginUser
{
get
{
var principal = HttpContext.User;
if (principal != null)
{
return new UserViewModel()
{
UserName = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value,
Mobile = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.MobilePhone)?.Value,
SysNo = new Guid(principal.Claims.FirstOrDefault(x => x.Type == "Id")?.Value ?? Guid.Empty.ToString())
};
}
return null;
}
}

使用ide

 var userId = CurrentLoginUser.SysNo;

startup類配置

在ConfigureServices方法添加

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath =new PathString("/User/Login");

});

在Configure方法添加

application.UseAuthentication();
application.UseAuthorization();

參考:

https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1

本文分享自微信公衆號 - dotNET知音(AAshiyou)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索