简体   繁体   中英

How to logout or expire JWT token for ASP.NET Core Web API?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM