我使用ASP.NET Core和ASP.NET Core Identity生成JWT令牌。
在客户端,我的React(SPA)应用程序调用API创建令牌,然后在子请求中包括Authorization: Bearer
来自API的令牌
。
当我想要注销时,如何立即使令牌在服务器端失效?
目前,我只是在客户端删除了bear
令牌,并不包含在下一个请求中。
参考:https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/
Startup.cs
文件中的Configure
部分代码:
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
[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);
}
}