.NET core3.1使用cookie进行身份认证
一個系統,用戶身份認證少不了,ASP.NET Core提供完整的解決方案Identity,用戶創建和維護登錄名;也提供能cookie和JwtBearer認證方案,當然你可以使用第三方認證Oauth、openId。項目沒有采用前后端分離,是一個標準的mvc項目,所以本文采用系統提供的cookie認證 記錄一下簡單認證流程,(1)使用用戶賬號密碼進行登錄,驗證合法登錄(2)確認合法身份之后,會頒發一個認證票據(加密)會攜帶與該用戶相關的身份、權限以及其他信息。(3)退出。
主要會使用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 。
用必要的 Claim來構造一個ClaimsIdentity,然后調用 SignInAsync 來登錄用戶。
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.創建聲明主題 指定認證方式 這里使用cookievar 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 ,并將其添加到當前響應中。
退出
退出很簡單,主要用戶清除cookie
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實例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
總結
以上是生活随笔為你收集整理的.NET core3.1使用cookie进行身份认证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Core + Kubernet
- 下一篇: .NET Core:跨平台和开源,让我在