ASP.NET Core and JWT token lifetime

22,248

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);
Share:
22,248
Alex Herman
Author by

Alex Herman

FREELANCER PROFILE — https://talent.hubstaff.com/profiles/aliaksei-herman ASP.NET MVC + jQuery, Knockout .NET Core + SPA apps using React, Angular, Vue My 5 projects on GitHub: feasible-ui — react-based UI toolkit written from scratch | not based on other UI libraries, serves as a boilerplate providing essential controls eixample — multi-tenant ASP.NET Core architecture: EF Core + PostgreSQL + React, Vue, Angular eixample_webapi2 — same as above, only for proprietary ASP.NET: EF + SQLServer + React, Vue, Angular pern-multitenancy — multi-tenant PERN architecture mern-multitenancy — multi-tenant MERN architecture

Updated on November 11, 2021

Comments

  • Alex Herman
    Alex Herman over 2 years

    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.

  • Alex Herman
    Alex Herman almost 6 years
    Thanks Alex, well played! Tested it several times trying different intervals - works.
  • Ameerudheen.K
    Ameerudheen.K almost 5 years
    How to avoid expiration? I have tried deleting expiry property but still it expires around 1 hour
  • AlexPi
    AlexPi almost 3 years
    ((JwtSecurityTokenHandler)tokenHandler).SetDefaultTimesOnTok‌​enCreation = false; to have it never expire.