Reputation: 16764
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 ?
Upvotes: 1
Views: 3622
Reputation: 1108
In server side create token method, use Utc time to generate expiration time:
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.UtcNow.AddMinutes(tokenValidityInMinutes),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
and in client side check for Utc time :
var identity = string.IsNullOrEmpty(tokenDTO?.Token) || tokenDTO?.Expiration < DateTime.UtcNow
In fact local time makes this problem, so you need to create an expiration time based on Utc and check it with DateTime.UtcNow
Upvotes: 0
Reputation: 22535
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.
Upvotes: 2