0

I have implemented basic token-based authentication in my asp.net Core web API project. I used JWT for authentication. I installed NuGet packages Microsoft.AspNetCore.Authentication.JwtBearer and Microsoft.AspNetCore.Authentication.JwtBearer. I follow this article step by step. The article code works fine if I set expire value as 10 mins.

I need to set the value as 1 minute or 2 minutes. I write code Expires = DateTime.UtcNow.AddMinutes(1). But after 1 minute complete the token still is valid.

Code: public Tokens Authenticate(Users users) {
  // other code here    
  var tokenHandler = new JwtSecurityTokenHandler();
  var tokenKey = Encoding.UTF8.GetBytes(iconfiguration["JWT:Key"]);
  var tokenDescriptor = new SecurityTokenDescriptor {
    Subject = new ClaimsIdentity(new Claim[] {
      new Claim(ClaimTypes.Name, users.Name)
    }),
    Expires = DateTime.UtcNow.AddMinutes(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature)
  };
  var token = tokenHandler.CreateToken(tokenDescriptor);
  return new Tokens {
    Token = tokenHandler.WriteToken(token)
  };
}

Startup.cs code

  services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                var Key = Encoding.UTF8.GetBytes(Configuration["JWT:Key"]);
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {                 
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["JWT:Issuer"],
                    ValidAudience = Configuration["JWT:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Key)                  
                };
               
            });
  • Please show your configuration for consuming the token. – ProgrammingLlama Jan 14 '22 at 16:09
  • this only code to generate token, In appsetting configuration Iuse below value, here xxx are some different value "JWT": { "Key": "xxxxxxxx", "Issuer": "xxxxx", "Audience": "xxxxx" } – Harman saab Jan 14 '22 at 16:18
  • OK, but how do you validate the token? – ProgrammingLlama Jan 14 '22 at 16:20
  • Using [Authorize] attribute over controller it validate, same i follow this https://codepedia.info/jwt-authentication-in-aspnet-core-web-api-token – Harman saab Jan 14 '22 at 16:21
  • 1
    most probably a clock skew issue, see accepted answer in the linked Q/A – jps Jan 14 '22 at 16:21
  • Then you are presumably using the authentication system in ASP.NET Core. Please look in your Startup.cs and provide the configuration code you have there for consuming these tokens. At the moment you have only shown the code for generating them. – ProgrammingLlama Jan 14 '22 at 16:22
  • In above they user app.UseJwtBearerAuthentication middleware, but i use only app.AddAuthentication – Harman saab Jan 14 '22 at 16:25
  • 1
    There isn't only one way to set up the validation parameters for validating JWT tokens. Without seeing how _you_ have it configured, it's impossible to answer your question. If you don't want to provide that, then I can't help you. – ProgrammingLlama Jan 14 '22 at 16:26
  • @Llama i added more code from startup cs. in accepted answer they use middleware my approach is different – Harman saab Jan 14 '22 at 16:27
  • 1
    Then your problem is the same one as jps linked to. The default value for `ClockSkew` (a property of `TokenValidationParameters`) is 5 minutes. Meaning that tokens will be accepted for 5 minutes after they expire. If you don't want that, you should set `ClockSkew = TimeSpan.Zero` as per [this answer](https://stackoverflow.com/a/44252312/3181933). – ProgrammingLlama Jan 14 '22 at 16:29
  • Ok i add ClockSkew and check – Harman saab Jan 14 '22 at 16:32
  • @Llama: thanks adding ClockSkew solved the problem, but this is strange cause ideally setting Expires = DateTime.UtcNow.AddMinutes(1) should override all default setting. Can you help me with refresh token, flow of refresh token after is expire – Harman saab Jan 14 '22 at 16:37
  • then please confirm that the linke Q/A answered your question (click on "yes, it answers..."). And please don't add new questions in a comment. Search for existing Q/A covering your refresh token topic and ask a new question, when you don't find an answer. – jps Jan 14 '22 at 16:39
  • You're looking at this the wrong way. Setting `Expires = someValue` is for _generating the token_. The other code is for _validating the token_. Sometimes the server receiving the token will not be the one that generated it. For example, we use Identity Server for authentication, and that's on a completely separate server and domain to our application code that validates the token. In such scenarios, setting some degree of `ClockSkew` may be desirable if the server clocks differ. – ProgrammingLlama Jan 14 '22 at 16:41
  • ok will do it and create new question on refresh token – Harman saab Jan 14 '22 at 16:41

0 Answers0