问题
There are many articles about revoking JWTs and many questions have been asked here before. This is the current scenario and how I solved it:
Users can sign in multiple times so they generate as many tokens as they want. Each token gets stored to the database after signing in. Whenever a user hits a protected endpoint the provided token gets validated for the signature and the lifetime. If everything was correct there is a database check if the token exists in the database. This is because if the user signs out a token still might be valid. So after signing out every user token gets removed from the database. With a cron job expired database tokens get removed automatically. The database table looks like
token | owner | expires_at
I'm thinking about simplifying this process:
Since you know that you will remove every token from a user after signing out I think the only thing you would have to check if any token exists for that user.
The user database table could have a column session_expires_at holding the maximum expiration time from the last token that was issued. The process would be
When signing in
Whenever generating a new token grab its expiration time and update the database column if this expiration time is greater than the value from session_expires_at
When hitting protected endpoints
Select the value from session_expires_at. The validation fails if that value is null or smaller than "now".
When signing out
Simply set session_expires_at for this user to null
It would still be possible to add a feature like "enable separate authentication per device". I'm focusing on the most import parts that came to my mind...
Advantages:
- No need for a token table, only a new column in the user table
- No need for storing every valid token, just update the session column for one user
Drawbacks:
- Reports are very limited. You can only read which user is currently signed in and which not.
I think this might simplify the authentication process for non enterprise projects. What do you think about it? Did I forget something?
来源:https://stackoverflow.com/questions/63068463/only-store-the-time-of-the-jwt-with-the-highest-lifetime-to-the-database-instead