Reputation: 945
For some reason my RESTful app allows requests from Angular client with expired token for some time. Generating 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);
}
on the client before request I log expiration time, now and if now more than expiration time. log of two successful requests, however the last one supposed to be failed
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 means expired
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
I only got refused after 5-6 minutes for some reason instead of 10 seconds.
Upvotes: 12
Views: 7187
Reputation: 1397
Where you define your TokenValidationParameters in Startup.cs, give the property ClockSkew a TimeSpan value of zero:
ClockSkew = TimeSpan.Zero, e.g:
new TokenValidationParameters
{
IssuerSigningKey = signingKey,
ValidIssuer = issuer,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
The reason for this is that ClockSkew has a default value of 5 minutes
Upvotes: 31