Asp.net Core Jwt使用总结(二)Jwt配置及使用详解
一、初始化配置数据
在appsettings.json文件中配置JWT节点,节点下创建SigningKey、ExpireSeconds两个配置项,分别代表JWT的密钥和过期时间(单位:秒)。
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "JWT": { "SecKey": "sdfarwer8sdf7sd6f6^#dfsdfdsf", "ExpireSeconds": 3600 } }
再创建配置类JWTOptions,包含SigningKey、ExpireSeconds两个属性。
namespace JWTTest { public class JWTOptions { public string SecKey { get; set; } public int ExpireSeconds { get; set; } } }
二、引入JWT包
Nuget:Microsoft.AspNetCore.Authentication.JwtBearer
三、在Program.cs文件中对JWT进行配置
//获取配置信息 services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT")); //Jwt校验配置 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(x => { var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>(); byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey); var secKey = new SymmetricSecurityKey(keyBytes); x.TokenValidationParameters = new() { ValidateIssuer=false, ValidateAudience=false, ValidateLifetime=true, ValidateIssuerSigningKey=true, IssuerSigningKey=secKey }; });
四、添加app.UseAuthentication()中间件
在Program.cs文件的app.UseAuthorization()这行代码之前添加app.UseAuthentication()
五、Controller类中进行登录测试
namespace JWTTest.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class LoginController : ControllerBase { //获取配置文件 private readonly IOptionsSnapshot<JWTOptions> jWTOptions; public LoginController(IOptionsSnapshot<JWTOptions> jWTOptions) { this.jWTOptions = jWTOptions; } /// <summary> /// 登录并返回Jwt代码 /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> [HttpPost] public ActionResult<string?> Login(string userName, string password) { if (userName == "admin" && password == "666666") { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, "1")); //读取配置文件 string key = jWTOptions.Value.SecKey; //超时时间 DateTime expires = DateTime.Now.AddSeconds(jWTOptions.Value.ExpireSeconds); byte[] secBytes = Encoding.UTF8.GetBytes(key); var secKey = new SymmetricSecurityKey(secBytes); var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature); var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expires, signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor); } else { return BadRequest(); } } } }
6、权限认证的使用
在需要登录才能访问的控制器类或者Action方法上添加[Authorize]
[HttpGet] [Authorize] public ActionResult<string?> Test1() { return "ok"; }
7、测试登录和访问。
用PostMan自定义报文头,Authorization的值为“Bearer JWTToken”, Authorization的值中的“Bearer”和JWT令牌之间一定要通过空格分隔。前后不能多出来额外的空格、换行等。
[Authorize]的注意事项
1、ASP.NET Core中身份验证和授权验证的功能由Authentication、Authorization中间件提供:app.UseAuthentication()、app.UseAuthorization() 。
2、控制器类上标注[Authorize],则所有操作方法都会被进行身份验证和授权验证;对于标注了[Authorize]的控制器中,如果其中某个操作方法不想被验证,可以在操作方法上添加[AllowAnonymous]。如果没有在控制器类上标注[Authorize],那么这个控制器中的所有操作方法都允许被自由地访问;对于没有标注[Authorize]的控制器中,如果其中某个操作方法需要被验证,我们也可以在操作方法上添加[Authorize]。
3、在Action方法内使用this.User.FindFirst(ClaimTypes.Name)获取JWT中的用户信息。
4、如果在Action方法上添加[Authorize(Roles=”admin”)],则要求用户必须有admin角色权限才可以访问。构造JWT时需要添加角色信息,claims.Add(new Claim(ClaimTypes.Role, "admin"));
5、ASP.NET Core会按照HTTP协议的规范,从Authorization取出来令牌,并且进行校验、解析,然后把解析结果填充到User属性中,这一切都是ASP.NET Core完成的,不需要开发人员自己编写代码。但是一旦出现401,没有详细的报错信息,很难排查,这是初学者遇到的难题。
本文附件(20230920143730JWTTest实例.rar)价格:¥0元
猜您可能还喜欢
- net core+webapi+nginx windows 服务器部署(1362)
- .Nuget Packages 太占C盘,删除后可以放到其他盘(1247)
- ASP.NET Core 配置 Swagger 显示接口注释描述信息(1143)
- vue调用接口后获取不到后端返回的Header响应头(1040)
- .net core 系列实例开发教程-权限管理系统功能介绍(992)
- .net core 6.0 web API + SwaggerUI + IIS部署(968)
- .net core 实例教程(十二)配置启用Swagger中的【Authorize】按钮(885)
- .net core 实例教程(一)新建项目(838)
- .net core 实例教程(十四)配置 Swagger 显示接口注释描述信息及支持版本控制(827)
- .net core 实例教程(十一)生成JWT格式的token密码配置及代码(803)
评论列表
发表评论
文章分类
文章归档
- 2025年3月 (1)
- 2024年6月 (2)
- 2024年5月 (2)
- 2024年4月 (4)
- 2024年3月 (30)
- 2024年1月 (4)
- 2023年12月 (2)
- 2023年11月 (4)
- 2023年10月 (4)
- 2023年9月 (6)
- 2023年3月 (2)
- 2023年2月 (1)
- 2023年1月 (1)
- 2022年12月 (1)
- 2022年9月 (21)
- 2022年8月 (10)
- 2022年7月 (3)
- 2022年4月 (1)
- 2022年3月 (13)
- 2021年8月 (1)
- 2021年3月 (1)
- 2020年12月 (42)
- 2020年11月 (7)
- 2020年10月 (5)
- 2020年8月 (1)
- 2020年6月 (1)
- 2020年3月 (2)
- 2019年12月 (8)
- 2019年11月 (3)
- 2019年9月 (1)
- 2019年4月 (1)
- 2019年3月 (6)
- 2019年2月 (1)
- 2018年7月 (7)
阅读排行
- 1.asp.net mvc内微信pc端、H5、JsApi支付方式总结(5751)
- 2.Windows 10休眠文件更改存储位置(3402)
- 3.各大搜索网站网站收录提交入口地址(3320)
- 4.ECharts仪表盘实例及参数使用详解(3220)
- 5.windows 10安装myeclipse 10破解补丁cracker.jar、run.bat闪退解决办法(3156)
- 6.HTML5 WebSocket与C#建立Socket连接实现代码(3015)
- 7.华为鸿蒙系统清除微信浏览器缓存方法(2926)
- 8.CERT_HAS_EXPIRED错误如何解决(2496)
- 9.Js异步async、await关键字详细介绍(lambda表达式中使用async和await关键字)(2344)
- 10.HBuilder编辑器格式化代码(2241)