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)
};
});