.net core 实例教程(十一)生成JWT格式的token密码配置及代码
本文源码下载地址:http://www.80cxy.com/Blog/ResourceView?arId=202403191532545995NAAqJh
系列教程地址:http://www.80cxy.com/Blog/ArticleView?arId=202403191517574161ay3s5V
本文实现访问接口秘钥功能,用户登录成功后,接口返回给前端JWT格式的秘钥,之后再访问其他接口需要提供秘钥,否则不允许访问。
一、JWT生成相关代码
在SignUp.Common项目创建JWT文件夹,在文件夹下面创建如下类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; //JWT秘钥生成接口 namespace SignUp.Common.JWT { public interface ITokenService { string BuildToken(IEnumerable<Claim> claims, JWTOptions options); } } //实现JWT接口 using Microsoft.IdentityModel.Tokens; using SignUp.Common.Extensions; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace SignUp.Common.JWT { public class TokenService : ITokenService { /// <summary> /// 生成JWT /// </summary> /// <param name="claims"></param> /// <param name="options"></param> /// <returns></returns> public string BuildToken(IEnumerable<Claim> claims, JWTOptions options) { TimeSpan ExpiryDuration = TimeSpan.FromSeconds(options.ExpireSeconds); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SecKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var tokenDescriptor = new JwtSecurityToken(options.Issuer, options.Audience, claims, expires: DateTime.Now.Add(ExpiryDuration), signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor); } /// <summary> /// 获取过期时间 /// </summary> /// <param name="jwtStr"></param> /// <returns></returns> public static DateTime GetExp( string jwtStr) { var jwtHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr); DateTime expDate = (jwtToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).GetInt().GetTimeSpmpToDate(); return expDate; } public static bool IsExp( string jwtStr) { return GetExp(jwtStr) < DateTime.Now; } } } //JWT配置参数类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SignUp.Common.JWT { public class JWTOptions { /// <summary> /// JWT Issuer /// </summary> public string Issuer { get ; set ; } /// <summary> /// JWT Audience /// </summary> public string Audience { get ; set ; } /// <summary> /// JWT SecKey /// </summary> public string SecKey { get ; set ; } /// <summary> /// JWT 过期时间 /// </summary> public int ExpireSeconds { get ; set ; } } } //注册服务 using Microsoft.Extensions.DependencyInjection; using SignUp.Common.Commons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SignUp.Common.JWT { class ModuleInitializer : IModuleInitializer { public void Initialize(IServiceCollection services) { services.AddScoped<ITokenService, TokenService>(); } } } |
二、配置JWT 在WebApplicationBuilderExtensions类的ConfigureExtraServices方法中增加如下代码:
1 2 3 | //JWT生成参数配置,从数据库读取 JWTOptions jwtOpt = configuration.GetSection( "JWT" ).Get(); services.Configure(configuration.GetSection( "JWT" )); |
学习交流
猜您可能还喜欢
- net core+webapi+nginx windows 服务器部署(1371)
- .Nuget Packages 太占C盘,删除后可以放到其他盘(1318)
- ASP.NET Core 配置 Swagger 显示接口注释描述信息(1153)
- vue调用接口后获取不到后端返回的Header响应头(1054)
- .net core 6.0 web API + SwaggerUI + IIS部署(997)
- .net core 系列实例开发教程-权限管理系统功能介绍(995)
- .net core 实例教程(十二)配置启用Swagger中的【Authorize】按钮(904)
- .net core 实例教程(一)新建项目(844)
- .net core 实例教程(十四)配置 Swagger 显示接口注释描述信息及支持版本控制(841)
- .net core 实例教程(十一)生成JWT格式的token密码配置及代码(835)
评论列表
发表评论
文章分类
文章归档
- 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支付方式总结(5766)
- 2.Windows 10休眠文件更改存储位置(3462)
- 3.各大搜索网站网站收录提交入口地址(3366)
- 4.ECharts仪表盘实例及参数使用详解(3238)
- 5.windows 10安装myeclipse 10破解补丁cracker.jar、run.bat闪退解决办法(3224)
- 6.HTML5 WebSocket与C#建立Socket连接实现代码(3053)
- 7.华为鸿蒙系统清除微信浏览器缓存方法(2975)
- 8.CERT_HAS_EXPIRED错误如何解决(2572)
- 9.Js异步async、await关键字详细介绍(lambda表达式中使用async和await关键字)(2402)
- 10.HBuilder编辑器格式化代码(2288)