出于某种原因,我的 RESTful 应用程序允许使用过期 token 的 Angular 客户端请求一段时间。 生成 token :
private async Task<string> GenerateJwtToken(ApplicationUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
claims.AddRange(await _userManager.GetClaimsAsync(user));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("SigningKey").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires =
DateTime.Now.AddSeconds(10);
//DateTime.Now.AddDays(Convert.ToDouble(_configuration["ExpireDays"]));
var token = new JwtSecurityToken(
issuer: _configuration["Issuer"],
audience: _configuration["Audience"],
claims: claims,
expires: expires,
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
在客户端请求之前我记录过期时间,现在和如果现在超过过期时间。两个成功请求的日志,但是最后一个应该失败
t: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time) credentials-service.ts:101
now: Tue Sep 18 2018 08:53:41 GMT+0300 (Moscow Standard Time) credentials-service.ts:102
false
true 表示已过期
credentials-service.ts:100 t: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time)
credentials-service.ts:101 now: Tue Sep 18 2018 08:58:01 GMT+0300 (Moscow Standard Time)
credentials-service.ts:102
true
出于某种原因,我只在 5-6 分钟后才被拒绝,而不是 10 秒。
最佳答案
在 Startup.cs 中定义 TokenValidationParameters 的位置,为属性 ClockSkew 指定一个 TimeSpan 值为零:
ClockSkew = TimeSpan.Zero,例如:
new TokenValidationParameters
{
IssuerSigningKey = signingKey,
ValidIssuer = issuer,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
这是因为 ClockSkew 的默认值为 5 分钟
关于c# - ASP NET Core JWT 身份验证允许过期 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379848/