Handling expiry/“remember me” functionality with JWT

后端 未结 6 531
忘掉有多难
忘掉有多难 2021-01-30 13:02

Conceptually, I really like JWT as it is in line with the statelessness of REST etc (no state saved server-side, all relevant data is contained in the token).

What I am

6条回答
  •  臣服心动
    2021-01-30 13:28

    In addition to @Jesus answer, you can think about implementing a refresh token system: https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/

    In the hotel-example, your hotel-card (access-token) would be invalid after time X, but at the reception you can use your passport (refresh-token) to get a new hotel card again.

    You could store the refresh token in the database with additional data about the device the user is using, allowing him to disable the device in case it gets stolen.

    Example:

    1. first correct client login: Create a refresh token which is valid forever (until it gets deleted or invalidated)
    2. store refresh token in database
    3. return access token (JWT) with expiration time to client ( this token gets not stored in database)
    4. for the next request, the client sends the access token

    5. Now Check if the access token is expired:

      5.1 Access Token not expired, all okay

      5.2 Access Token expired, check if there is a refresh token in database

      5.2.1 Refresh Token is in database, return new Access Token

      5.2.2 No Refresh Token in database, return 401 / logout, User has to login again

    Hope this helps.

提交回复
热议问题