I am currently using the JwtSecurityToken class in System.IdentityModels.Tokens namespace. I create a token using the following:
DateTime expires = DateTime.Utc
This is handled slightly differently in .NET Core, as the TokenValidationParameters
are set in Startup.cs
using the ConfigureServices()
method and then handled automatically by the middleware.
Also note that the older InMemorySymmetricSecurityKey
for signing the secret is now deprecated in favor of SymmetricSecurityKey
, which is shown below.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = _config.AuthenticationSettings.TokenAuthority,
ValidAudience = _config.AuthenticationSettings.TokenAuthority,
LifetimeValidator = TokenLifetimeValidator.Validate,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_config.AuthenticationSettings.SecurityKey))
};
});
// ...
}
And so I also made my own version of the token validator in @tkd_aj's answer above and threw it in a static class:
public static class TokenLifetimeValidator
{
public static bool Validate(
DateTime? notBefore,
DateTime? expires,
SecurityToken tokenToValidate,
TokenValidationParameters @param
) {
return (expires != null && expires > DateTime.UtcNow);
}
}