. NET Core 5项目与RestAPI,我使用JWT承载令牌和刷新令牌。我这样配置启动:
var jwtSecretKey = Configuration.GetValue<string>("Jwt:Key");
var key = Encoding.UTF8.GetBytes(jwtSecretKey);
var tokenValidationParameters = new TokenValidationParameters
{
SaveSigninToken = true,
ValidateActor = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key),
// set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = tokenValidationParameters;
});
为了生成令牌,我使用了以下代码(需要注意的是,我使用了UTC)日期):string validIssuer = _configuration["Jwt:Issuer"];
string validAudience = _configuration["Jwt:Audience"];
var jwtSecretKey = _configuration.GetValue<string>("Jwt:Key");
var issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecretKey));
var accessTimeout = _configuration.GetValue<int>("Jwt:MinutosExpiracionTokenAcceso");
DateTime fechaHoy = DateTime.UtcNow;
DateTime fechaExpiracionToken = DateTime.UtcNow.AddMinutes(accessTimeout);
var userRoles = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) // (JWT ID) Unique Identifier for JWT, can be used to prevent the JWT from being replayed. Is best suited for refresh tokens
};
foreach (var userRole in userRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
}
var token = new JwtSecurityToken(
validIssuer,
validAudience,
claims,
fechaHoy,
fechaExpiracionToken,
new SigningCredentials(issuerSigningKey, SecurityAlgorithms.HmacSha256)
);
var refreshTimeout = _configuration.GetValue<int>("Jwt:MinutosExpiracionTokenAutorizacion");
var refreshToken = new RefreshToken()
{
JwtId = token.Id,
IsUsed = false,
UserId = user.Id,
AddedDate = DateTime.UtcNow,
ExpiryDate = DateTime.UtcNow.AddMinutes(refreshTimeout),
IsRevoked = false,
Token = RandomString(25) + Guid.NewGuid()
};
await _unitOfWork.GetRepository<RefreshToken>().AddAsync(refreshToken);
await _unitOfWork.SaveChangesAsync();
var tokensDto = new TokensResponseDto
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
RefreshToken = refreshToken.Token
};
return tokensDto;
我正面临验证令牌的问题(_tokenValidationParameters与启动时使用的相同):
var jwtTokenHandler = new JwtSecurityTokenHandler();
ClaimsPrincipal principal = null;
SecurityToken validatedToken = null;
principal = jwtTokenHandler.ValidateToken(tokenRequest.Token, _tokenValidationParameters, out validatedToken);
无论我是否使用本地时间(如DateTime),它都会抛出没有特定日期的上述异常。现在不是UTC。
我尝试通过在TokenValidationParameters中添加LifetimeValidator来启动,像这样:
LifetimeValidator = (DateTime? notBefore,
DateTime? expires,
SecurityToken securityToken,
TokenValidationParameters validationParameters
) =>
{
if (expires != null)
{
if (DateTime.UtcNow < expires.Value.ToUniversalTime())
{
return true; // Still valid
}
}
return false; // Expired
}
然而,ValidateToken失败,出现以下异常:
IDX10230:生存期验证失败。委托返回false, securitytoken: ' system . identitymodel . token . jwt . jwtsecuritytoken '.
谢谢你的帮助
我也遇到过类似的问题。我的服务器(生成令牌)时间和客户端(消耗令牌)时间不同。同步,运行完美。
在我的例子中,当我在一个Linux服务器上部署应用程序时,我有一个类似的" idx10222 ";此错误背后的原因是服务器当前时间运行在令牌创建时间之后,因此服务器无法验证令牌。
例如- Token创建时间- 10:00:00 on dd:MM:yyyy UTC,Linux服务器时间- 08:00:00 on dd:MM:yyyy UTC
然后我们得到这个错误-生存期验证失败。该令牌还无效。
请检查您的机器日期时间并修复,如果它与当前时间不同步。
你试试吧:
/*
ClaimsPrincipal principal = null;
principal = jwtTokenHandler.ValidateToken(tokenRequest.Token, _tokenValidationParameters, out validatedToken);
*/
validatedToken = jwtTokenHandler.ReadJwtToken(token);
/*Your own validation logic*/