網站首頁 編程語言 正文
在實際使用中,可能會遇到,aspi接口驗證和view頁面的登錄驗證情況。asp.core 同樣支持兩種兼容。
首先在startup.cs 啟用身份驗證。
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,//是否驗證Issuer ValidateAudience = true,//是否驗證Audience ValidateLifetime = true,//是否驗證失效時間 ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true,//是否驗證SecurityKey ValidAudience = Configuration["JWTDomain"],//Audience ValidIssuer = Configuration["JWTDomain"],//Issuer IssuerSigningKey = secrityKey//拿到SecurityKey }; });
Configure 方法中須加入
app.UseAuthentication(); //授權 app.UseAuthorization(); //認證 認證方式有用戶名密碼認證 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頁面,后臺代碼
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 = "用戶密碼不正確" //創建一個身份認證 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 身份認證處理 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 }
注意, 受身份驗證的控制器部分,要加入如下屬性頭,才可以生效。
[Authorize(AuthenticationSchemes = "Bearer,Cookies")] public class ControllerCommonBase : ControllerBase { }
這樣一個Controler 控制器,能夠兼容兩種模式啦。
原文鏈接:https://www.cnblogs.com/voidobject/p/15890764.html
相關推薦
- 2022-09-04 ffmpeg網頁視頻流m3u8?ts實現視頻下載_相關技巧
- 2023-03-28 Python中list列表添加元素的3種方法總結_python
- 2023-07-10 Bean的生命周期和作用域
- 2024-01-28 springboot登錄認證JWT令牌
- 2022-11-16 docker-compose安裝及執行命令_docker
- 2022-05-09 go單例實現雙重檢測是否安全的示例代碼_Golang
- 2022-03-22 C語言字符串函數入門_C 語言
- 2022-12-25 利用pycharm調試ssh遠程程序并實時同步文件的操作方法_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支