Wendell
Wendell

Reputation: 180

How to force expire a JWT token in ASP.Net Core?

I have implemented a JWT authentication and a policy-based authorization in ASP.NET Core. There is a certain user with admin privileges who can assign permissions to non-admin users. If the admin updates the permissions/claims of a non-admin user, is there a way to force expire the access token so that user carrying it will be forced to request a new access token with the newly updated permissions/claims? Right now, the only way to that is to wait for the token to expire but I want to force expire it immediately.

Upvotes: 3

Views: 4287

Answers (2)

No, there is no direct method to expire the JWT before the set expiry time at the time of creation.

But there are some common techniques to invalidate the JWT tokens,

  1. Blacklisting

Implement a blacklist where invalidated tokens are kept. When a user logs out, or when a token needs to be expired forcibly, add that to the blacklist. Check this blacklist whenever a request with a JWT is being made.

  1. Token Versioning

You will add a version field to your tokens and then store the version in your database. When you want to force expire a token, you will increase the token version in the database. On each request, check if the token version matches the one stored in the database

Upvotes: 0

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

Authentication based on JWT tokens is stateless in serverside. So when a token is not expired it will work. There are some approaches to the problem:

  • Not including the roles and permissions in the token claims and getting these values from the database in each request.
  • Using refresh token mechanism and set a refreshing time to a few minutes and return a new token when refreshing time is expired. Therefore for the tokens with the expired refreshing time you know to get the new access permissions(not in each request). New permissions will set in few minutes but the authenticated user doesn't need to log in again.
  • Creating a set of black-list tokens and append the last issued token to that (not recommended).

Upvotes: 2

Related Questions