Is a Refresh Token really necessary when using JWT token authentication?

后端 未结 3 1463
萌比男神i
萌比男神i 2021-01-29 19:51

I am referencing another SO post that discusses using refresh tokens with JWT.

JWT (JSON Web Token) automatic prolongation of expiration

I have an application wi

3条回答
  •  不要未来只要你来
    2021-01-29 20:45

    I believe for this scenario you could work with the access token alone, making life easier for your clients but keeping the security benefits of a refresh token.

    This is how it would work:

    1. When your user logs in with credentials (username/password) you return a short-lived JWT. You also create a db record where you store:

      • JWT id
      • user id
      • IP address
      • user agent
      • a valid flag (defaults to TRUE)
      • createdAt
      • updatedAt
    2. Your client submits the JWT in every request. As long as the JWT hasn't expired, it has access to the resources. If the JWT expired, you refresh it behind the scenes and return both the resource and an additional X-JWT header with the new JWT.

    3. When the client receives a response with an X-JWT header, it discards the old JWT and uses the new one for future requests.

    How refreshing the JWT works on the server

    1. Look for the matching db record using the JWT id.
    2. Check if the valid flag is still true, otherwise reject.
    3. Optionally, you can compare the request IP address and user agent against the stored IP address and user agent, and decide to reject if something looks fishy.
    4. Optionally, you can check the db record's createdAt or updatedAt fields, and decide not to refresh if too much time has passed.
    5. Update the updatedAt field in the db record.
    6. Return the new JWT (which is basically a copy of the expired JWT, but with an extended expiration time).

    This design would also give you the option to revoke all tokens for a user (for example, if the user loses his phone or updates his password).

    Benefits:

    • Your client never has to check expiration times or make refresh token requests, all it does is check for an X-JWT header on responses.
    • You can add custom refresh logic based on IP address, user agent, max-token age, or a combination of those.
    • You can revoke some or all tokens for a user.

提交回复
热议问题