Adding ClockSkew = TimeSpan.Zero
to token validation parameters solved my issue.
ASP.NET Core Web API - Reading JWT

Cenk
1,036
Reputation points
Hello,
I implemented JWT authentication. Setting userId into the claim.
[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 != null)
{
//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", user.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();
}
}
And reading it as follows:
[HttpGet]
[Route("reconciliation")]
public async Task<IActionResult> GameReconciliation([FromForm] ReconciliationDto reconciliationDto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var userId = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
...
I wonder if is this a good practice. By the way, JWT token doesn't expire how can I fix it?
Developer technologies ASP.NET ASP.NET Core
4,815 questions
1 answer
Sort by: Most helpful
-
Cenk 1,036 Reputation points
2022-12-24T15:11:14.847+00:00