【NetCore】Net6 Jwt 鉴权
2022/2/22 6:24:51
本文主要是介绍【NetCore】Net6 Jwt 鉴权,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Jwt 鉴权
基本:生成一个 Token
// 以下信息需要与鉴权的地方一致 var key = "1234567890123456"; Claim[] claims = new[] { new Claim("user", username) }; var keyBytes = Encoding.UTF8.GetBytes(key); var creds = new SigningCredentials( new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256 ); var jwtSecurityToken = new JwtSecurityToken( issuer: "wosperry.com", audience: "wosperry.com", claims: claims, expires: DateTime.Now.AddMinutes(5), // 五分钟后过期 signingCredentials: creds ); var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
封装部分信息到配置文件
- 定义
Options
类
public class TokenOptions { public string SecretKey { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public int ExpireMinutes { get; set; } = 30; }
- 在
appsettings.json
添加相关的配置
{ "TokenOptions": { "SecretKey": "123456789456789456", "Issuer": "wosperry.com", "Audience": "wosperry.com", "ExpireMinutes": 2 } }
- 封装服务
// 接口 public interface IJwtService { Task<string> CreateTokenAsync(string username); } // 实现 public class JwtService : IJwtService { public TokenOptions TokenOptions { get; } public JwtService(IOptions<TokenOptions> options) { TokenOptions = options.Value; } public Task<string> CreateTokenAsync(string username) { // 添加一些需要的键值对 Claim[] claims = new[] { new Claim("user", username) }; var keyBytes = Encoding.UTF8.GetBytes(key); var creds = new SigningCredentials( new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256 ); var jwtSecurityToken = new JwtSecurityToken( issuer: TokenOptions.Issuer,// 签发者 audience: TokenOptions.Audience,// 接收者 claims: claims,// payload expires: DateTime.Now.AddMinutes(TokenOptions.ExpireMinutes),// 过期时间 signingCredentials: creds);// 令牌 var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); return Task.FromResult(token); } }
- 入口配置
var section = builder.Configuration.GetSection("TokenOptions"); // 获取TokenOptions配置 var tokenOptions = section.Get<TokenOptions>(); builder.Services.AddTransient<IJwtService, JwtService>(); // 注册Jwt服务到容器 builder.Services.Configure<TokenOptions>(section); // 注入IOptions需要这个 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否在令牌期间验证签发者 ValidateAudience = true,//是否验证接收者 ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证签名 ValidAudience = tokenOptions.Audience,//接收者 ValidIssuer = tokenOptions.Issuer,//签发者,签发的Token的人 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecretKey)) }; });
- 请求管道配置( 注意顺序 !!! )
// 注意顺序,不然 401 app.UseAuthentication(); app.UseAuthorization();
- 方便
swagger
设置 Header
builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new() { Title = "Perry测试用", Version = "v1", Description = "Perry测试用\r\nPerry测试用\r\nPerry测试用\r\n" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", Name = "Authorization", In = ParameterLocation.Header, Scheme = "bearer", Type = SecuritySchemeType.Http, BearerFormat = "JWT" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new List<string>() } }); });
博客园:https://www.cnblogs.com/wosperry/p/net6_jwt.html
这篇关于【NetCore】Net6 Jwt 鉴权的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具