Could we destroy JWT token in Asp.NET Core?

I use ASP.NET Core & ASP.NET core Identity to generate JWT token.

In client side, my react (SPA) app call API to create the token then include Authorization: Bearer tokenFromApi in subrequests.

When I want to logout how can I immediately expire the token in server side?

Currently I just delete the bear token in 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 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:

  • Cache the token's ID once the token is created with a duration as long as the expiration time of the token (both, access and refresh token)
  • [If Farm/multiple instances]You need to cache it in a distributed cache, like redis
  • [If Farm/multiple instances]You need to propagate it via message bus (ie using Redis, RabbitMQ or Azure Message Bus) to every instance of your application, so they can store it in a local memory cache (so you don't have to have a network call, each time you want to validate it)
  • During authorization, you need to validate if the ID is still inside the cache; if not, refuse authorization (401)
  • When user logs out, you need to remove your item from the cache.
  • [If Farm/multiple instances]Remove the item from the distributed cache and send a message to all instances so they can remove it from their local cache
  • 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.

    链接地址: http://www.djcxy.com/p/22434.html

    上一篇: Cookie身份验证不适用于asp.net核心中的授权策略

    下一篇: 我们可以在Asp.NET Core中销毁JWT令牌吗?