Alex Herman
Alex Herman

Reputation: 2848

ASP.NET Core and JWT token lifetime

I utilize ASP.NET Core 2.1.1

It is interesting that the expiration time is only being taken into account when one provides both ClockSkew - in Startup.cs and JwtSecurityTokenHandler.TokenLifetimeInMinutes - in a controller.

For instance:

services
  .AddJwtBearer(x =>
  {
      ...
      x.TokenValidationParameters = new TokenValidationParameters()
      {
         ClockSkew = TimeSpan.FromMinutes(90),
         ...

plus

...
public async Task<AuthenticateOutput> Authenticate([FromBody] AuthenticateInput input)
{
   var tokenHandler = new JwtSecurityTokenHandler();
   tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes;
   ...

If I remove tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes; part - the default expiration time is used.

It seems to me that tokenHandler.TokenLifetimeInMinutes is still redundant and I just misunderstand the concept of how to set the expiration time correctly.

I also tried adding expiration claim - new Claim(ClaimTypes.Expiration, ...) - but that didn't have much effect.

Upvotes: 14

Views: 28156

Answers (2)

KingRaja
KingRaja

Reputation: 194

//reading the key from config
//reading the issuer from config
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(configuration["Jwt:Issuer"], configuration["Jwt:Issuer"], 
                            null, expires: DateTime.Now.AddMinutes(60),
                            signingCredentials: credentials); //60mins expiration 

            string newToken = new JwtSecurityTokenHandler().WriteToken(token);

Upvotes: 0

Alex Riabov
Alex Riabov

Reputation: 9195

ClockSkew property isn't about expiration itself, it compensates for clock skew.

To setup token expiration you have to specify it on token creation:

new JwtSecurityToken(
                ...
                expires: DateTime.UtcNow.AddMinutes(90),
                ....);

and the following code will give you string with token:

var token = new JwtSecurityToken() { /* setup your token setting here*/ }
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

Upvotes: 30

Related Questions