The code below works fine at generating new tokens from a valid token but not an expired one.
[HttpPost]
[Route("refreshtoken")]
public async Task<IActionResult> RefreshToken()
{
var identity = User.Identity as ClaimsIdentity;
var username = identity.FindFirst("user");
if (username.Value != null)
{
var user = await _userManager.FindByNameAsync(username.Value);
var token = GenerateToken(user);
return Ok(token);
}
return BadRequest("Could not refresh token");
}
As soon as I try to refresh an invalid token I get the error message NullReferenceException: Object reference not set to an instance of an object
. Having looked at the error logs then username.Value == null
so it appears I am unable to get claims from an expired token.
Is there a better way to generate a refresh token from expired tokens?
What you would like to do is extract the principle of the token itself, something along the lines of this:
//Create the token handler for the JWT validation
var tokenHandler = new JwtSecurityTokenHandler();
//Try and validate the token
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out _);
Once you have the principal of the token you can extract the specific claims from it such as the user. To get the email for instance you can do something along the lines of:
var emails = principal.Claims.First(c => c.Type == ClaimTypes.Email).Value;