.NET core3.1使用cookie进行身份认证
一個(gè)系統(tǒng),用戶身份認(rèn)證少不了,ASP.NET Core提供完整的解決方案Identity,用戶創(chuàng)建和維護(hù)登錄名;也提供能cookie和JwtBearer認(rèn)證方案,當(dāng)然你可以使用第三方認(rèn)證Oauth、openId。項(xiàng)目沒有采用前后端分離,是一個(gè)標(biāo)準(zhǔn)的mvc項(xiàng)目,所以本文采用系統(tǒng)提供的cookie認(rèn)證 記錄一下簡單認(rèn)證流程,(1)使用用戶賬號(hào)密碼進(jìn)行登錄,驗(yàn)證合法登錄(2)確認(rèn)合法身份之后,會(huì)頒發(fā)一個(gè)認(rèn)證票據(jù)(加密)會(huì)攜帶與該用戶相關(guān)的身份、權(quán)限以及其他信息。(3)退出。
主要會(huì)使用Microsoft.AspNetCore.Authentication.Abstractions包中 AuthenticationHttpContextExtensions類,它是基于HttpContext上公開身認(rèn)證的擴(kuò)展法:
| SignInAsync | 登錄用戶.用戶登錄成功后頒發(fā)一個(gè)證書(加密的用戶憑證,這個(gè)憑證放入Cookie中),用來標(biāo)識(shí)用戶的身份 |
| SignOutAsync | 注銷退出.清除Cookie |
| GetTokenAsync | 用來獲取 AuthenticationProperties 中保存的額外信息 |
| ForbidAsync | 通知用戶權(quán)限不足,如果是ajax請(qǐng)求返回403狀態(tài)碼,不是ajax請(qǐng)求跳轉(zhuǎn)指定的url |
| ChallengeAsync | 通知用戶需要登錄。在默認(rèn)實(shí)現(xiàn)類AuthenticationHandler中,返回401 |
| AuthenticateAsync | 驗(yàn)證在 SignInAsync 中頒發(fā)的證書,并返回一個(gè) AuthenticateResult 對(duì)象,表示用戶的身份。 |
登錄創(chuàng)建一個(gè)cookie認(rèn)證
這里涉及幾個(gè)對(duì)象:Claim聲明常常代表,認(rèn)證用戶身份的元數(shù)據(jù)信息,比如手機(jī)號(hào)、郵箱、用戶名等等。ClaimsIdentity聲明主體,代表一個(gè)認(rèn)證用戶的身份證,當(dāng)然包含聲明的集合。ClaimsPrincipal身份證持有者。
流程:創(chuàng)建一個(gè)包含用戶信息的 cookie需要構(gòu)造一個(gè)ClaimsPrincipal。將序列化用戶信息并將其存儲(chǔ)在中 cookie 。
用必要的 Claim來構(gòu)造一個(gè)ClaimsIdentity,然后調(diào)用 SignInAsync 來登錄用戶。
public async Task<Result> UserLogin([FromForm] UserLoginInput input){//登錄邏輯var model = userService.UserLogin(input);//1.創(chuàng)建cookie 保存用戶信息,使用claim。將序列化用戶信息并將其存儲(chǔ)在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.創(chuàng)建聲明主題 指定認(rèn)證方式 這里使用cookievar claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);//3.配置認(rèn)證屬性 比如過期時(shí)間,是否持久化。。。。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,//持久化 ,比如 登錄的時(shí)候 勾選記住我 復(fù)選框//IssuedUtc = <DateTimeOffset>,//絕對(duì)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 創(chuàng)建一個(gè)加密的 cookie ,并將其添加到當(dāng)前響應(yīng)中。
退出
退出很簡單,主要用戶清除cookie
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);獲取認(rèn)證信息
登錄之后,我們通常會(huì)獲取一些聲明中的信息,可以使用 HttpContext.User 將會(huì)返回一個(gè)ClaimsPrincipal對(duì)象
ClaimsPrincipal principal = HttpContext.User;if (null != principal){foreach (Claim claim in principal.Claims){var ii = "CLAIM TYPE: " + claim.Type + "; CLAIM VALUE: " + claim.Value + "</br>";}}統(tǒng)一處理獲取到的信息,賦值UserViewModel實(shí)例CurrentLoginUser
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;}}使用
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
總結(jié)
以上是生活随笔為你收集整理的.NET core3.1使用cookie进行身份认证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Core + Kubernet
- 下一篇: .NET Core:跨平台和开源,让我在