我使用 ASP.NET Core & ASP.NET core Identity 来生成 JWT token 。
在客户端,我的 React (SPA) 应用程序调用 API 来创建 token ,然后包含 Authorization: Bearer
token from API
在子请求中。
当我想注销时,如何立即使服务器端的 token 失效?
目前,我只是删除了 bear
客户端的 token 并且不包含在下一个请求中?
引用 : https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/
代码在 Configure
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
}
});
创建 token 的 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);
}
}
最佳答案
您不能轻易让它过期,而不会失去它的一些优势或使解决方案变得更加复杂。
最好的办法是使访问 token 时间足够短(<= 5 分钟)并且刷新 token 长时间运行。
但是,如果您真的想立即使其无效,则需要做一些事情:
其他不需要消息总线/分布式缓存的解决方案将需要在每个请求上联系身份验证服务器,从而扼杀了 JWT token 的主要优势。
JWT 的主要优点是它们是自包含的,Web 服务不必调用另一个服务来验证它。它可以通过验证签名在本地进行验证(因为用户不能在不使签名无效的情况下更改 token )和 token 的到期时间/受众。
关于authentication - 我们可以在 Asp.NET Core 中销毁/无效 JWT token 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45748732/