Search code examples
apijwt

JwtSecurityToken expiration date is two hours apart


In my .net core api application, I use:

var dt = DateTime.Now.AddMinutes(60); // time is 2018-04-27 14:49:00

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var claims = new[]
              {
                 new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                 new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
              };

var token = new JwtSecurityToken(
        _config["Tokens:Issuer"], 
        _config["Tokens:Audience"], 
        claims,
        expires: dt,
        signingCredentials: creds);

token.ValidTo is shown as 2018-04-27 12:49:00 ...

Why ?


Solution

  • It's because of the different timezones. Your timezone is probably UTC+2, and your variable dt contains the time in local time.

    But JwtSecurityToken.ValidTo is a DateTime value which contains a time in UTC. The resulting JWT will give you a value (exp claim) based in Unix Epoch Time in seconds sine 1970-01-01 00:00 UTC. In your case exp will be

    1524833340

    which equals

    2018-04-27 12:49:00 UTC (14:49 in UTC+2)

    as you can check here and the JWT framework knows how to handle that, independent from the timezone.

    The behaviour is correct and you don't need to change anything.