目录
前言
本文主要讲述了在.net core下实现JWT授权以及Token失效之后如何刷新Token,关于JWT请参考如下文章JWT,TODO:萌新劝退,本文需要具有一定的基础知识。照抄可能你会什么都不懂。
以下正文:
StartUp中ConfigureServices注册
#region jwt
//读取Jwt 配置文件
services.Configure<JwtSetting>(Configuration.GetSection("JwtSettings"));
//绑定到实例中
var jwt = new JwtSetting();
Configuration.Bind("JwtSettings", jwt);
//添加身份验证
services.AddAuthentication(options =>
{
//认证middleware配置
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
//Token颁发机构
ValidIssuer = jwt.Issuer,
//颁发给谁
ValidAudience = jwt.Audience,
//这里的key要进行加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecretKey)),
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = true,//是否验证失效时间
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ClockSkew = TimeSpan.Zero,//校验时间是否过期时,设置的时钟偏移量
};
//捕捉令牌过期
o.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("act", "expired");
}
return Task.CompletedTask;
}
};
});
#endregion
Appsetting配置,参数需自定义
"JwtSettings": {
"Issuer": "",
"Audience": "",
"SecretKey": "",
"AccessTokenExpiresMinutes": "35",
"RefreshTokenAudience": "RefreshTokenAudience",
"RefreshTokenExpiresMinutes": "240" //4Сʱ
}
JwtSetting类
/// <summary>
/// Jwt
/// </summary>
public class JwtSetting
{
/// <summary>
/// token是谁颁发的
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// token可以给那些客户端使用
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 加密的key(SecretKey必须大于16个,是大于,不是大于等于)
/// </summary>
public string SecretKey { get; set; }
/// <summary>
/// token过期时间
/// </summary>
public string AccessTokenExpiresMinutes { get; set; }
/// <summary>
/// refresh Token
/// </summary>
public string RefreshTokenAudience { get; set; }
/// <summary>
/// refresh Token exprise
/// </summary>
public string RefreshTokenExpiresMinutes { get; set; }
}
StartUp中Configure注入身份授权,需在UseMvc之前
//身份授权认证
app.UseAuthentication();
登入方法
/// <summary>
/// 获取Token
/// </summary>
/// <param name="users"></param>
/// <returns></returns>
private async Task<AccountRes> GetTokenAsync(Users users)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(jwt.SecretKey);
var authTime = DateTime.Now;
var expiresAt = authTime.AddMinutes(double.Parse(jwt.AccessTokenExpiresMinutes));
var tokenDescripor = new SecurityTokenDe