Only store the time of the JWT with the highest lifetime to the database instead of the whole JWT

回眸只為那壹抹淺笑 提交于 2021-02-05 05:53:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!