NetCoreNet6 Jwt 鉴权
Posted wosperry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NetCoreNet6 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>()
);
);
以上是关于NetCoreNet6 Jwt 鉴权的主要内容,如果未能解决你的问题,请参考以下文章