Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revoke JWT Bearer Token in .net core API

I have implemented JWT Bearer token base authentication and authorization. I am using the below code for destroying the JWT token or logout the current user but it's not working.

//var claim = _httpContextAccessor.HttpContext.User.Claims;
            // var users = await _userManager.FindByNameAsync(_httpContextAccessor.HttpContext.User.Identity.Name);
            //  var identity = _httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
            // foreach (var item in claim)
            // {
            //     identity.RemoveClaim(item);
            // }

            await _signInManager.SignOutAsync();
like image 342
Sumit Rawat Avatar asked Oct 30 '22 02:10

Sumit Rawat


1 Answers

It is not possible to cancel/revoke a JWT token during user's logout, it is not straightforward, but there is a workaround to that. You can try following the steps below:

  • Set a reasonable expiration time on tokens
  • Delete the stored token from client side upon log out
  • Have DB of no longer active tokens that still have some time to live
  • Query provided token against The Blacklist on every authorized request

I am also pasting 2 links below that myself found very helpful:

  • How to log out when using JWT
  • Canceling JWT tokens in .NET Core
like image 94
vasilisdmr Avatar answered Jan 02 '23 19:01

vasilisdmr