Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JWT using UTC-time using .NET Core

Currently I am programming a ASP.NET-Core WebApi using JWT-Bearer-Authentication.

To make the API accessible from different timezones I am using the following Pattern to set the fields nbf (notBefore) and exp (expires) inside my JWT to a UTC-Timestamp:

var utcNow = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);

...

var tokenOptions = new JwtSecurityToken(
                notBefore: utcNow,
                expires: utcNow.AddSeconds(3600),
            );
...

For token generation, everything works pretty good, nbf and exp contain a UNIX-Timestamp representing the current UTC-Time.

But when doing token validation, everything works for 5 Minutes (my clock-skew setting) and then I only get 401 from API, because the token-validation is done with my current timezone here in Germany.

Is there a way to setup the JwtAuthentication-Middleware in .NET-Core to use UTC-Time for token-validation? Or are there any other ways to solve this?

like image 814
DevElch Avatar asked Mar 25 '19 15:03

DevElch


People also ask

How does JWT verify token at time of login?

We must send the access token to the OneLogin OIDC app's introspection endpoint to validate the token. If the token is valid, the introspection endpoint will respond with an HTTP 200 response code. The body of the response will also contain an augmented version of the original JWT token's payload.

How do you validate that a JWT is valid?

To verify JWT claimsVerify that the token is not expired. The aud claim in an ID token and the client_id claim in an access token should match the app client ID that was created in the Amazon Cognito user pool. The issuer ( iss ) claim should match your user pool.

What is JWT token in .NET core?

JSON Web Tokens (commonly known as JWT) is an open standard to pass data between client and server, and enables you to transmit data back and forth between the server and the consumers in a secure manner.


1 Answers

For a more complete answer, in your Startup.cs:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                // ...
                ValidateLifetime = true,
                LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, 
                                     TokenValidationParameters validationParameters) => 
                {
                    return notBefore <= DateTime.UtcNow &&
                           expires >= DateTime.UtcNow;
                }
            };
        });
like image 196
Serj Sagan Avatar answered Sep 29 '22 15:09

Serj Sagan