Search code examples
c#identityserver4identityasp.net-core-5.0

Unable to understand IdentityTokenLifetime and how long my JWT lasts


I'm unable to understand how long the JWT token lives.

  • IdentityTokenLifetime (Lifetime of identity token in seconds (defaults to 300 seconds / 5 minutes)

= 120 / 60 = 2 minutes

What's the purpose of IdentityTokenLifetime?

  • AccessTokenLifetime (Lifetime of access token in seconds (defaults to 3600 seconds / 1 hour)

= 120 / 60 = 2 minutes

  • SlidingRefreshTokenLifetime (Sliding lifetime of a refresh token in seconds. Defaults to 1296000 seconds / 15 days)

= 300 / 60 = 5 minutes

Judging by the weird summary comment information, I don't really understand how long the JWT token lives in minutes.

public static IEnumerable<Client> GetClients(IConfiguration configuration) =>
    new List<Client>
    {
        new()
        {
            ClientName = configuration["AuthConfiguration:ClientName"],
            ClientId = configuration["AuthConfiguration:ClientId"],
            ClientSecrets = { new Secret(configuration["AuthConfiguration:ClientSecret"].Sha256()) },

            AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
            AccessTokenType = AccessTokenType.Jwt,
            AllowOfflineAccess = true,

            AccessTokenLifetime = 120,
            IdentityTokenLifetime = 120,
            UpdateAccessTokenClaimsOnRefresh = true,
            SlidingRefreshTokenLifetime = 300,
            RefreshTokenExpiration = TokenExpiration.Absolute,
            RefreshTokenUsage = TokenUsage.OneTimeOnly,
            AlwaysSendClientClaims = true,

            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.OfflineAccess,
                configuration["AuthConfiguration:ApiName"]
            }
        }
    };

Solution

  • From your example, once authentication succeeds, the following tokens are created:

    1. Refresh Token that expires in 300 seconds. The value TokenExpiration.Absolute means that the Refresh Token will not be refreshed. This is normally too short of a value. Refresh Tokens typically last for days. Once the Refresh Token expires, no more tokens can be refreshed and the user will need to authenticate again.
    2. Access Token that expires in 120 seconds. Provided that the Refresh Token has not expired, a new Access Token will be created.
    3. Identity Token that expires in 120 seconds. Provided that the Refresh Token has not expired, a new Identity Token will be created.

    To obtain lifetime in minutes for each token divide seconds by 60.