I followed your JWT tutorial. But the token somehow doesn't expire, how can I fix it?
Here is the Program.cs:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidIssuer = builder.Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
Here is the token controller:
[Route("api/token")]
[ApiController]
public class TokenController : Controller
{
private readonly IUserValidate _userValidate;
private readonly IConfiguration _config;
public TokenController(IUserValidate userValidate, IConfiguration config)
{
_userValidate = userValidate;
_config = config;
}
[HttpPost]
public async Task<IActionResult> Post([FromForm]string username, [FromForm] string password)
{
if (username != null && password != null)
{
var user = _userValidate.Login(username, password);
if (user)
{
//create claims details based on the user information
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, _config["Jwt:Subject"]),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
//new Claim("UserId", _company.customerID.ToString()),
new Claim("DisplayName", username),
new Claim("UserName", username),
//new Claim("Email", _company.Email)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Jwt:Issuer"],
_config["Jwt:Audience"],
claims,
expires: DateTime.UtcNow.AddMinutes(1),
signingCredentials: signIn);
return Ok(new JwtSecurityTokenHandler().WriteToken(token));
}
else
{
return BadRequest("Invalid credentials");
}
}
else
{
return BadRequest();
}
}
}