我将JWT设置为3小时过期,但过期时间过早(不到2分钟)
string _keys = JWT.Key;
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_keys));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
double _minutes = Security.Minute_JWT_Expiry;
var token = new JwtSecurityToken(JWT.Issuer, JWT.Key,
null,
expires: DateTime.UtcNow.AddMinutes(180),
signingCredentials: credentials);
return await Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token));
答案 0 :(得分:0)
只想分享: 之所以出现此问题,是因为我将值与DateTime.Now ..进行了比较。
if (expires.HasValue)
return expires.Value > DateTime.UtcNow;
完成:
var key = Encoding.ASCII.GetBytes(JWT.Key);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = false,
ValidIssuer = JWT.Issuer,
LifetimeValidator =
(before, expires, token, parameters) =>
{
if (before.HasValue && before.Value > DateTime.Now)
return false;
if (expires.HasValue)
return expires.Value > DateTime.UtcNow;
//Otherwise the token is valid
return true;
},
ValidateLifetime = true,
};
});