问题
This question may sound stupid but I still wanna know what else I can do to achieve this functionality.
There's an inventory system built as a REST API and there are two types of users.
users
admins
Let's say when an user logs in, he's given a JWT token that contain following information.
email
, user_id
, user_level
This token is decoded in each private route and checks if the user is authenticated and also checks the user level to make sure the user is authorized to access that particular resource.
Let's consider a special scenario that an admin (Admin A) logs in and start doing some admin stuff on the system. Suddenly another admin (SuperAdmin) wants to downgrade Admin A to a normal user for some reason. However, even-though now Admin A is just a normal user, his token is still an Admin token. So, he can still do admin stuff until the token automatically expires in one hour.
So, in a scenario like this what's the way to expire that token manually ? Does the system should use a DB query to check user level for each admin route ? Or is there any other way to achieve this ?
Hope you get this clearly.
回答1:
One viable way to handle this would be to maintain a cache consisting of JWT/state of users whose rights have been changed since their initial JWT were issued. The workflow would typically go something like this:
- Your system issues an admin JWT to a certain user
- For a while, that admin uses his JWT as usual
- Then a super admin decides to downgrade the admin. Since he cannot revoke his JWT, instead he writes an entry to a blacklist cache, recording that this user is no longer an admin.
- From this point forward, the server will first check all incoming requests against the blacklist cache to decide which information to use. In the case of the example admin, the server would discover a cache entry and then only give this user normal non admin rights.
- Assuming your JWT have an expiry date, the cache will eventually remove stale JWT, keeping the memory footprint as small as possible.
The key point here regarding the cache is that it is fast. Accessing an entry in the cache should be roughly 100 times faster than hitting a database. As for expiring stale entries in the cache, many cache implementations, such as Redis, allow for setting the expiry of an entry when it gets written. In this case, the server would just set the expiry using the exp
claim inside the original JWT. If setup properly, the memory requirements of the cache can be kept to a minimum.
来源:https://stackoverflow.com/questions/60462856/how-to-expire-a-jwt-token-manually