authentication - 我们可以在 Asp.NET Core 中销毁/无效 JWT token 吗?

标签 authentication asp.net-core .net-core jwt asp.net-core-identity

我使用 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 长时间运行。

但是,如果您真的想立即使其无效,则需要做一些事情:

  • 创建 token 后缓存 token 的 ID,持续时间与 token 的过期时间(访问 token 和刷新 token )
  • 【如果Farm/多实例】需要缓存在分布式缓存中,比如redis
  • [如果农场/多个实例]您需要通过消息总线(即使用 Redis、RabbitMQ 或 Azure 消息总线)将其传播到应用程序的每个实例,以便它们可以将其存储在本地内存缓存中(因此您没有有一个网络调用,每次你想验证它)
  • 授权时,需要验证ID是否还在缓存中;如果没有,拒绝授权 (401)
  • 当用户注销时,您需要从缓存中删除您的项目。
  • [如果农场/多个实例]从分布式缓存中删除项目并向所有实例发送消息,以便他们可以将其从本地缓存中删除

  • 其他不需要消息总线/分布式缓存的解决方案将需要在每个请求上联系身份验证服务器,从而扼杀了 JWT token 的主要优势。

    JWT 的主要优点是它们是自包含的,Web 服务不必调用另一个服务来验证它。它可以通过验证签名在本地进行验证(因为用户不能在不使签名无效的情况下更改 token )和 token 的到期时间/受众。

    关于authentication - 我们可以在 Asp.NET Core 中销毁/无效 JWT token 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45748732/

    相关文章:

    java - 当服务器超时时,如何使weblogic中经过身份验证的 session 失效?

    security - 哈希和登录

    c# - 在 Razor 网页上显示静态 .png 图像

    .net - .NET Core 的地理空间库?

    nlog - 是否有 Trace.CorrelationManager 的 .NET 标准等效项?

    algorithm - 由 Mashery 实现的 API 签名认证是如何工作的?

    authentication - 如何使用 Owin 安全性从针对 WebAPI 的自动化测试中进行身份验证?

    c# - 异常 : Correlation failed. 未知位置

    c# - .NET Core 2.1 中的 HttpContext.GetTokenAsync 无法检索 JWT

    c# - 无法在 dotnet 核心 Entity Framework 中导入 OleDbConnection