網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
asp.core?同時(shí)兼容JWT身份驗(yàn)證和Cookies?身份驗(yàn)證兩種模式(示例詳解)_實(shí)用技巧
作者:至道中和 ? 更新時(shí)間: 2022-04-19 編程語(yǔ)言在實(shí)際使用中,可能會(huì)遇到,aspi接口驗(yàn)證和view頁(yè)面的登錄驗(yàn)證情況。asp.core 同樣支持兩種兼容。
首先在startup.cs 啟用身份驗(yàn)證。
var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"])); services.AddSingleton(secrityKey); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(option => //cookies 方式 { option.LoginPath = "/Login"; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => //jwt 方式 { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否驗(yàn)證Issuer ValidateAudience = true,//是否驗(yàn)證Audience ValidateLifetime = true,//是否驗(yàn)證失效時(shí)間 ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true,//是否驗(yàn)證SecurityKey ValidAudience = Configuration["JWTDomain"],//Audience ValidIssuer = Configuration["JWTDomain"],//Issuer IssuerSigningKey = secrityKey//拿到SecurityKey }; });
Configure 方法中須加入
app.UseAuthentication(); //授權(quán) app.UseAuthorization(); //認(rèn)證 認(rèn)證方式有用戶名密碼認(rèn)證 app.MapWhen(context => { var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" }; //注意小寫 return context.Request.Path.HasValue && context.Request.Path.Value.Contains("Login") && context.Request.Headers.ContainsKey("Authorization") && !(excludeUrl.Contains(context.Request.Path.Value.ToLower())); }, _app => { _app.Use(async (context, next) => { context.Response.StatusCode = 401; }); });
在login頁(yè)面,后臺(tái)代碼
var uid = Request.Form["code"] + ""; var pwd = Request.Form["pwd"] + ""; var info = _mysql.users.Where(m => m.user_code == uid&&m.delflag==0).FirstOrDefault(); if (info == null) { return new JsonResult(new { success = false, msg = "用戶不存在" }); } if (info.pwd != pwd) msg = "用戶密碼不正確" //創(chuàng)建一個(gè)身份認(rèn)證 var claims = new List<Claim>() { new Claim(ClaimTypes.Sid,info.id), //用戶ID new Claim(ClaimTypes.Name,info.user_code) //用戶名稱 }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); //var identity = new ClaimsIdentity(claims, "Login"); //var userPrincipal = new ClaimsPrincipal(identity); //HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties //{ // ExpiresUtc = DateTime.UtcNow.AddMinutes(30), // IsPersistent = true //}).Wait(); var authProperties = new AuthenticationProperties //AllowRefresh = <bool>, // Refreshing the authentication session should be allowed. ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60), // The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie. IsPersistent = true, // Whether the authentication session is persisted across // multiple requests. When used with cookies, controls // whether the cookie's lifetime is absolute (matching the // lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> // The full path or absolute URI to be used as an http // redirect response value. }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
Controler控制器部分,登錄代碼:
[HttpPost("Login")] public async Task<JsonResult> Login(getdata _getdata) { var userName = _getdata.username; var passWord = _getdata.password; var info = _mysql.users.Where(m => m.user_code == userName && m.delflag == 0).FirstOrDefault(); if (info == null) { return new JsonResult(new { state = false, code = -1, data = "", msg = "用戶名不存在!" }); } if (CommonOp.MD5Hash(info.pwd).ToLower() != passWord) code = -2, msg = "用戶密碼不正確!" #region 身份認(rèn)證處理 var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["SecurityKey"])); List<Claim> claims = new List<Claim>(); claims.Add(new Claim("user_code", info.user_code)); claims.Add(new Claim("id", info.id)); var creds = new SigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: _config["JWTDomain"], audience: _config["JWTDomain"], claims: claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: creds); return new JsonResult(new state = true, code = 0, data = new JwtSecurityTokenHandler().WriteToken(token), msg = "獲取token成功" }); #endregion }
注意, 受身份驗(yàn)證的控制器部分,要加入如下屬性頭,才可以生效。
[Authorize(AuthenticationSchemes = "Bearer,Cookies")] public class ControllerCommonBase : ControllerBase { }
這樣一個(gè)Controler 控制器,能夠兼容兩種模式啦。
原文鏈接:https://www.cnblogs.com/voidobject/p/15890764.html
相關(guān)推薦
- 2023-03-29 詳解C++中菱形繼承的原理與解決方法_C 語(yǔ)言
- 2022-07-20 SQL?Server中搜索特定的對(duì)象_MsSql
- 2022-07-14 Android檢測(cè)手機(jī)多點(diǎn)觸摸點(diǎn)數(shù)的方法_Android
- 2022-02-10 微信小程序this.triggerEvent(),父組件中使用子組件的事件
- 2022-05-06 matplotlib繪制兩點(diǎn)間連線的幾種方法實(shí)現(xiàn)_python
- 2022-03-27 Python的輸出格式化和進(jìn)制轉(zhuǎn)換介紹_python
- 2022-05-27 Python必備技巧之集合Set的使用_python
- 2022-05-19 Nginx+Windows搭建域名訪問(wèn)環(huán)境的操作方法_nginx
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支