Skip to content

How are DateTime values treated?

BrentSchmaltz edited this page Mar 10, 2022 · 3 revisions

DateTime values used by this library are expected to be in UTC. If a DateTime is not in UTC, it will be converted to UTC.

For example, when creating a token using JsonWebTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor), the DateTime properties on the SecurityTokenDescriptor (Expires, IssuedAt, and NotBefore) will all be converted to UTC during the token creation process.

A Claim created from a JSON datetime string, represented in format defined by the ISO 8061, will have ClaimValueTypes.DateTime as a value type.

A Claim created from a JSON datetime string, represented in formats other than the format defined by the ISO 8061, will have ClaimValueTypes.String as a value type.

Issue when using DateTimeOffset. Consider the following code:

JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(expires: DateTimeOffset.UtcNow.DateTime.AddMinutes(15));

The DateTime instance passed to the ctor, will have the UTC time, but the Kind property will be DateTimeKind.Unspecified. Internally

EpochTime.GetIntDate(DateTime);

will get called which will call DateTime.ToUniversalTime(). Most likely this is not what the use wants. The following will work as expected.

JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(expires: DateTimeOffset.DateTime.AddMinutes(15));
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(expires: DateTime.UtcNow.AddMinutes(15));
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(expires: DateTime.Now.AddMinutes(15));
Clone this wiki locally