Base solution for your next web application
Open Closed

How to Expire Token #5015


User avatar
0
ni3rk created

We want to expire token, How we can expire.


6 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    You can configure it in the ConfigureTokenAuth method of *WebCoreModule:

    tokenAuthConfig.Expiration = TimeSpan.FromDays(1);
    
  • User Avatar
    0
    bbakermmc created

    I assume they want to expire the token after its been issued, which I dont believe there is a way w/out making a table of tokens and validating them there.

  • User Avatar
    0
    ni3rk created

    Can u Please guide me , How and where i can Check coming in every request ? i will create table and save token in it , and at logout i will remove it but , I need to check For every request ?

  • User Avatar
    0
    alper created
    Support Team

    Are you using MVC or Core?

    As far as I know you can write custom token validator for JWT

    public class CustomJwtSecurityTokenHandler : ISecurityTokenValidator
        {
            private int _maxTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;
            private JwtSecurityTokenHandler _tokenHandler;
    
            public CustomJwtSecurityTokenHandler()
            {
                _tokenHandler = new JwtSecurityTokenHandler();
            }
    
            public bool CanValidateToken
            {
                get
                {
                    return true;
                }
            }
    
            public int MaximumTokenSizeInBytes
            {
                get
                {
                    return _maxTokenSizeInBytes;
                }
    
                set
                {
                    _maxTokenSizeInBytes = value;
                }
            }
    
            public bool CanReadToken(string securityToken)
            {
                return _tokenHandler.CanReadToken(securityToken);
            }
    
            public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
            {
                //How to access HttpContext/IP address from here?
    
                var principal = _tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken);
    
                return principal;
            }
        }
    

    And add this validator in AuthConfigurer.cs

    if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
                {
                    authenticationBuilder.AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            // The signing key must match!
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),
    
                            // Validate the JWT Issuer (iss) claim
                            ValidateIssuer = true,
                            ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],
    
                            // Validate the JWT Audience (aud) claim
                            ValidateAudience = true,
                            ValidAudience = configuration["Authentication:JwtBearer:Audience"],
    
                            // Validate the token expiry
                            ValidateLifetime = true,
    
                            // If you want to allow a certain amount of clock drift, set that here
                            ClockSkew = TimeSpan.Zero
    
                        };
    
                        //**** add your custom validator here ****
                        options.SecurityTokenValidators.Clear();
                        options.SecurityTokenValidators.Add(new CustomJwtSecurityTokenHandler());
    
                        options.Events = new JwtBearerEvents
                        {
                            OnTokenValidated = context =>
                            {
                                /*You can also throw exceptin if you want to prohibit user */
                                return Task.CompletedTask;
                            }
                        };
                    });
                }
    

    There's OnTokenValidated event in the JWT Options that you can check your business logic and throw ex if you want.

    But as a result, I couldn't succeed in intercepting token validation. But this may inspire you...

    PS: Previously asked here #2952

  • User Avatar
    0
    ni3rk created

    Thanks

  • User Avatar
    0
    alper created
    Support Team

    no prob.