Restrict user to use Expired token

Jan 01, 2024

Here, I will explain how to restrict users from using expired tokens in a .NET Core application.
Token expiration checks are crucial for ensuring the security of your application.
 

Here's a general outline of how you can achieve this:

1. Configure Token Expiration:
When generating a token, such as a JWT, set an expiration time for the token. This is typically done during token creation. For example, when using JWTs, you can specify the expiration claim:

 

var tokenDescriptor = new SecurityTokenDescriptor
{
    Expires = DateTime.Now.AddMinutes(30) // Set expiration time
};



2. Token Validation Middleware:
Create middleware in your application to validate the token on each request.

This middleware should verify the token's expiration time. You can configure this middleware in the startup or program file on the .NET side.
 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<TokenExpirationMiddleware>();
}


3. Token Expiration Middleware:
Develop middleware to validate the token's expiration time.

Take note of the following points:
ValidateIssuerSigningKey: Set to true, indicating that the system should validate the issuer signing key.

IssuerSigningKey: The byte array represents the secret key used for both signing and verifying the JWT token.

ValidateIssuer and ValidateAudience: Set to false, indicating that validation of the issuer and audience is skipped.

By setting ClockSkew to TimeSpan.Zero, you specify no tolerance for clock differences. If the current time on the server or client is not precisely within the token's validity period, the token is considered expired. 


    public class TokenExpirationMiddleware
    {
        private readonly RequestDelegate _next;

        public TokenExpirationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            // Check if the request has a valid token
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (token != null)
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("YourSecretKey"); // Replace with your actual secret key of Issuer
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                };

                try
                {
                    // Validate the token
                    var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);

                    // Check if the token is expired
                    if (securityToken is JwtSecurityToken jwtSecurityToken)
                    {
                        if (jwtSecurityToken.ValidTo < DateTime.Now)
                        {
                            // Token is expired
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            return;
                        }
                    }
                }
                catch (SecurityTokenException)
                {
                    // Token validation failed
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return;
                }
            }
            await _next(context);
        }
    }


Working fine with proper token time.


Here is an example: I am providing an expired token, and it will result in a 401 Unauthorized status.


You can also check the token in https://jwt.io/ for time expired (exp) .


By following these steps, you can effectively implement checks to ensure that users are not able to use expired tokens within your .NET Core application.

Himanshu Pranami

About the Author

Himanshu Pranami

I'm working as a Software Developer at MagnusMinds IT Solution. I bring 3+ years of professional experience to the table. My expertise spans a range of technologies, including .NET Framework, .NET Core, MVC, ASP.NET, Entity Framework, ADO.NET, SQL, PostgreSQL, C#, Azure DevOps, and Microservices.