在令牌验证中,我检查了令牌的生命周期,它是 13:07:10 。当我运行验证时, 13:12 并且验证成功。的为什么吗
当它大约是 13:15 时,我再次运行验证并按预期抛出异常。
令牌是否有最短到期时间?
创建令牌:
var token = new JwtSecurityToken(
issuer: token_issuer,
audience: token_audience,
claims: claims,
expires: DateTime.Now.AddSeconds(5),
signingCredentials: creds
);
验证令牌:
private static bool ValidateToken(string token)
{
try
{
TokenValidationParameters validationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(token_salt),
ValidAudience = token_audience,
ValidIssuer = token_issuer,
RequireExpirationTime = true
};
ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);
return true;
}
catch(SecurityTokenExpiredException ex)
{
}
return false;
}
答案 0 :(得分:0)
在 .net core 中,jwt 中间件将最小默认过期时间设置为 5 分钟。您可以在启动时的令牌参数验证选项中更改它。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])),
ClockSkew = TimeSpan.FromMinutes(0) //---- this item help ypu to set or reset default value
};
});