3

I have created a token with:

 IdentityOptions identityOptions = new IdentityOptions();
 var claims = new Claim[]
 {
     new Claim(identityOptions.ClaimsIdentity.UserIdClaimType,  token.User.FirstOrDefault().ID.ToString()),
     new Claim(identityOptions.ClaimsIdentity.UserNameClaimType,request.Local.UserName),
 };

 var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this-is-my-secret-key"));
 var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
 var jwt = new JwtSecurityToken(signingCredentials: signingCredentials, claims: claims, expires: DateTime.Now.AddHours(12));

Can you help me how to logout or expire this token for ASP.NET Core Web API? So the user will never use this token again.

Thanks

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • Does this answer your question? [JWT Token: logout JWT token](https://stackoverflow.com/questions/61368789/jwt-token-logout-jwt-token) – Yong Shun Apr 30 '21 at 04:45
  • Yong I have already checked it but its not useful for me . There are remove for the db . – sandeep maheshwari Apr 30 '21 at 04:52
  • 1
    You can't expire or cancel the JWT token because you don't track the token, That's the pros of the JWT. You should think of it while issuing the token. – qazwsx123 Apr 30 '21 at 06:37

1 Answers1

3

Once JWT is generated and sent to the client. It cannot be change already (not by client itself and must go through back-end to get a new token).

In order to invalidate/revoke a JWT, you may have a Redis (recommended) or database to store those invalidated JTI (Token ID) that is associated with each JWT issued.

If you do not wish to have Redis/database, then you must keep your JWT lifetime as short as possible like 5 minutes. Then, when logout, remove the token from client side (local storage or cookie). However, this approach does not invalidate JWT immediately, clients are still able to access to the API if they keep their token before we remove it.

GanHJ
  • 330
  • 1
  • 4
  • 8