I use ASP.NET Core & ASP.NET core Identity to generate a JWT token.
On the client-side, my React (SPA) app calls API to create the token then include Authorization: Bearer
token from API
in subrequests.
When I want to logout, how can I immediately invalidate the token on the server-side?
Currently, I just delete the bear
token on the client-side and not included in the next request?
Reference: https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/
Code in Configure
section in Startup.cs
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "MySite",
ValidAudience = "MySite",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE")),
ValidateLifetime = true
}
});
API to create a token
[HttpPost("Token")]
public async Task<IActionResult> CreateToken([FromBody] LoginModel model)
{
try
{
var user = await userManager.FindByNameAsync(model.Email);
if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
"MySite",
"MySite",
claims,
expires: DateTime.UtcNow.AddMinutes(45),
signingCredentials: creds);
return Ok(new
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
});
}
return BadRequest();
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
You can't easily have it expire, w/o losing some of the advantages of it or making the solution significantly more complex.
Best bet is to make the access token time short enough (<= 5 mins) and the refresh token long running.
But if you really want to invalidate it immediately, you would need a few things:
Other solutions not requiring message bus/distributable cache would require to contact the auth server on every single request, killing the main advantage of an JWT token.
The main advantage of JWT is that they are self-contained and a web service do not have to call another service to validate it. It can be validated locally by validating the signature (since the token can't be changed by the user w/o invalidating the signature) and expiration time/audience the token is meant for.