发布时间:2022-04-05 10:58:55来源:本站阅读(703)
.NET6发布后,逐步也使用.NET6开始做项目了。最近一个API项目,使用JWT做了权限验证
上代码
Program里
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidAudience = "zhhrdao",
ValidIssuer = "zhhrdao",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder .Configuration.GetValue("JwtSecurityKey"))),
ClockSkew = TimeSpan.Zero
};
//监听JWT过期事件
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
//context.Response.Headers.Add("jwtexception", "expired");
}
return Task.CompletedTask;
}
};
});
以上代码我没有验证Issuer、Audience、Lifetime所以设置了false,lifetime不验证的话监听过期事件也就没必要了。
然后在要验证的controller或action 上加特性
[Authorize]
如果不需要验证则加
[AllowAnonymous]
如何获取token ?往下看
[HttpPost("gettoken")]
public string GetTk()
{
var m = new ParamsBase { UserId = 999, UserCode = "admin", UserName = "dao", CompanyId = 10049, DeptId = 100000 };
var token=JWTHelper.WriteToken(m,_config.GetValue("JwtSecurityKey"));
return token;
}
///
///
///
/// 用户信息
/// JWT密钥
/// 过期时间,单位:秒
///
public static string WriteToken(ParamsBase model,string jwtSecKey,long expires=30)
{
//用户信息
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, model.UserId.ToString()),
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.PostalCode,model.UserCode),
new Claim(ClaimTypes.Country,model.CompanyId.ToString()),
new Claim(ClaimTypes.GroupSid,model.DeptId.ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "zhhrdao",
audience: "zhhrdao",
claims: claims,
expires: DateTime.Now.AddSeconds(expires),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
调用接口里在header里传入 Authorization:Bearer {token} 即可。
关键字: authorize
1651
1624
1866
1563
1518
1432
1070
1884
1322
1063
9598
6001
5528
5122
4573
4276
3421
3340
3339
3274