Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 416
Alex Herman Avatar asked Jul 15 '18 06:07

Alex Herman


People also ask

What happens when JWT token expires .NET core?

Option 1 after token expiration, the user re-login by passing username and password and get the new access token. Option 2 using Refresh token re-generate new JWT access token and consume the secured API (without re-login).

What is the lifespan of JWT token?

May 3, 2022 When using the Okta authorization server, the lifetime of the JWT tokens is hard-coded to the following values: ID Token: 60 minutes. Access Token: 60 minutes. Refresh Token: 100 days.

How can I make my JWT token last longer?

A good pattern is to refresh the token before it expires. Set the token expiration to one week and refresh the token every time the user opens the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.


1 Answers

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);
like image 196
Alex Riabov Avatar answered Sep 28 '22 11:09

Alex Riabov