Search code examples
access-tokenidentityserver4

Identity server 4 access token with custom lifetime


I have a scenario where I have to return custom access token to a user who has not validated his/her email. Access token has to expire after 24 hours regardless of access token lifetime specified for a client.

Is there a way to specify lifetime of access token per quest. I already have "IResourceOwnerPasswordValidator" interface implemented.

One option I came across is to to use Identity server tools "IdentityServerTools" to generate a token but don't know how to return proper token response with refresh token(which still needs to be generated).

var token = await _identityServerTools.IssueClientJwtAsync(
                clientId: context.Request.Client.ClientId,
                lifetime: 86400, // 24 hours in seconds
                scopes: context.Request.Scopes
            );

Solution

  • The following code is not tested but it could be a solution:

    internal class YourCustomTokenRequestValidator : ICustomTokenRequestValidator
    {
        // your email checker which takes an `IClaimsPrincipal` parameter
        private readonly IEmailChecker emailChecker;
        public YourCustomTokenRequestValidator(IEmailChecker emailChecker)
        {
            this.emailChecker = emailChecker;
        }
        public Task ValidateAsync(CustomTokenRequestValidationContext context)
        {
            var request = context.Result.ValidatedRequest;
            var isVerified = false;
            var subject = request.Subject ?? request.AuthorizationCode?.Subject;
            if(subject != null)
            {
               isVerified = emailChecker.IsVerified(subject);
               if (!isVerified)
               {
                  request.AccessTokenLifetime = 24 * 60 * 60;
               }
            } 
    
            return Task.CompletedTask;
        }
    }
    

    Register custom implementation:

    services.AddIdentityServer()
               .AddCustomTokenRequestValidator<YourCustomTokenRequestValidator>()
                /// ;