我已经在。net 5 Web API项目和Angular 11的前端中创建了JWT授权/认证服务,我面临的一个问题是刷新令牌功能。当我发送刷新令牌请求时。我正在使用微软提供的JwtSecurityTokenHandler类中的验证令牌函数,如果令牌已经过期,它会抛出异常,所以我的问题是,我应该在它过期之前发送刷新令牌请求吗?如果没有,我怎么能禁用令牌过期检查在验证令牌功能,或者我应该写我自己的版本的功能?
您可以很容易地禁用令牌过期检查。只需创建新的TokenValidationParameters
并将ValidateLifetime
设置为false。像这样
public ClaimsPrincipal GetPrincipalFromExpiredToken(string jwtToken)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = configuration["security:audience"],
ValidIssuer = configuration["security:issuer"],
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetIssuerSigningKey(),
ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(jwtToken, tokenValidationParameters, out SecurityToken securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
throw new SecurityTokenException("Invalid token");
return principal;
}