Reputation: 111
Using JWT tokens, I was working on authentication for my .NET Core API. I was wondering if I can tell my API to ignore the expiry of my token when the user requests a certain route, like "/refresh" for example, to refresh expired tokens. I understand it can be worked around by supplying the tokens through a POST request, but I want the ability to ignore the expiry of a token when I only want to identify the calling user.
My code is done as below. Currently it works with a POST request but I want the ability to supply expired tokens through the header.
[AllowAnonymous]
[HttpPost("refresh")]
public async Task<IActionResult> Refresh(RefreshRequest refreshRequest)
{
// Validate refresh token
if (!_tokenService.RefreshTokenValid(refreshRequest.Refresh_Token)) {
return BadRequest("The request token is not a valid token.");
}
var tokenHandler = new JwtSecurityTokenHandler();
// Validate actual token
if (!tokenHandler.CanReadToken(refreshRequest.Token)) {
return BadRequest("The JWT token is not a valid token.");
}
// Get the user from the JWT token
var userId = _tokenService.GetUserIdFromtoken(refreshRequest.Token);
var repoUser = await _repo.GetUserById(userId);
// Map the user, generate a token and send response
var newToken = _tokenService.GenerateRefreshedJwtToken(repoUser);
var tokenUser = _mapper.Map(repoUser, new AuthRefreshedTokenUser(newToken));
return Ok(tokenUser);
}
Upvotes: 3
Views: 2192
Reputation: 27528
A simple way is to create another authentication schema and set not to validate token's lifetime :
.AddJwtBearer(options =>
{
...
options.TokenValidationParameters.ValidateLifetime = false;
....
});
And apply that authentication scheme using [Authorize(AuthenticationSchemes = "schemeName")]
on specific controllers/actions.
Upvotes: 4