日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET core3.1使用cookie进行身份认证

發(fā)布時間:2023/12/4 asp.net 61 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET core3.1使用cookie进行身份认证 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

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

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

登錄創(chuàng)建一個cookie認證

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

流程:創(chuàng)建一個包含用戶信息的 cookie需要構造一個ClaimsPrincipal。將序列化用戶信息并將其存儲在中 cookie 。

用必要的 Claim來構造一個ClaimsIdentity,然后調用 SignInAsync 來登錄用戶。

public async Task<Result> UserLogin([FromForm] UserLoginInput input){//登錄邏輯var model = userService.UserLogin(input);//1.創(chuàng)建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.創(chuàng)建聲明主題 指定認證方式 這里使用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 創(chuàng)建一個加密的 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>";}}

統(tǒng)一處理獲取到的信息,賦值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进行身份认证的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。