我们可以在Asp.NET Core中销毁/无效JWT令牌吗?

问题描述 投票:5回答:1

我使用ASP.NET Core和ASP.NET核心Identity来生成JWT令牌。

在客户端,我的react(SPA)应用程序调用API来创建令牌,然后在子请求中包含Authorization: Bearer tokenFromApi

当我想注销时如何立即使服务器端的令牌过期?

目前我只删除客户端的bear令牌而不包括在下一个请求中?

参考:https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/


ConfigureStartup.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

[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);
    }
}
authentication asp.net-core .net-core jwt asp.net-core-identity
1个回答
10
投票

你不能轻易地让它过期,不会失去它的一些优点或使解决方案显着更复杂。

最好的办法是让访问令牌时间足够短(<= 5分钟)并且刷新令牌长时间运行。

但如果你真的想立即使它失效,你需要一些东西:

  1. 创建令牌后缓存令牌的ID,持续时间与令牌的到期时间一样长(访问和刷新令牌)
  2. [If Farm / multiple instances]您需要将其缓存在分布式缓存中,例如redis
  3. [If Farm / multiple instances]你需要通过消息总线(即使用Redis,RabbitMQ或Azure消息总线)将它传播到应用程序的每个实例,这样它们就可以将它存储在本地内存缓存中(所以你没有有网络电话,每次你要验证它)
  4. 在授权期间,您需要验证ID是否仍在缓存中;如果没有,拒绝授权(401)
  5. 用户注销时,您需要从缓存中删除项目。
  6. [If Farm / multiple instances]从分布式缓存中删除项目并向所有实例发送消息,以便他们可以将其从本地缓存中删除

其他不需要消息总线/可分发缓存的解决方案需要在每个请求上联系auth服务器,从而破坏了JWT令牌的主要优势。

JWT的主要优点是它们是自包含的,并且Web服务不必调用另一个服务来验证它。它可以通过验证签名在本地进行验证(因为用户无法更改令牌,无法使签名无效)以及令牌所针对的到期时间/受众。

© www.soinside.com 2019 - 2024. All rights reserved.