12

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.

Alexander Kozachenko
  • 885
  • 2
  • 13
  • 26
  • 1
    Find the ClockSkew setting in the token validation settings ;) Those usually allow a little bit off time to account for server clocks being out of sync. – juunas Sep 18 '18 at 06:06
  • 1
    you should use ClockSkew for example as shown here - https://stackoverflow.com/questions/46129183/jwtauthentication-not-working-in-asp-net-core-2-0-after-migrate-from-1-1-to-2-0 – Алексей Сидоров Sep 18 '18 at 08:31

1 Answers1

30

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

MattjeS
  • 1,367
  • 18
  • 35