skip to Main Content

We are going to implement a Node.js-based authentication system using access tokens and refresh tokens. Here is the flow:

  1. The user logs in with their username and password. If the credentials are valid, the system returns an access token and a refresh token.
  2. The access token has a lifespan of one hour, and the refresh token has a lifespan of one week.
  3. When the user tries to access a protected resource using the access token, the system validates the token and provides the resource if it’s valid.
  4. If the access token is invalid, the system returns an unauthorized response.
  5. The user can create a new access token by providing the refresh token.
  6. If the refresh token is valid, the system returns a new access token.

The above steps are the normal flow, but in our case, we need to implement force logout and logout from all devices.

Our plan is:

  • Create a session table in Redis and store the token and user ID in Redis when the user logs in.
  • When the user tries to access a protected resource, we will validate the token and check if the token and user ID are present in the Redis session.
  • When the user logs out, we will remove that token from the Redis session.
  • When the user hits "logout from all devices," we will remove all tokens of that particular user from the Redis session.

We have a few questions:

  • Is the above method good or bad? Are there any more efficient ways?
  • In the above method, do we really need a refresh token? Since each time we need to hit the Redis session table with the access token and refresh token for validation.

2

Answers


  1. Create a session table in Redis

    This pretty much sums up your requirement. What you’re actually after are sessions, not tokens. If there is no particular reason for using access and refresh tokens, then go with plain old HTTP sessions. Then you can quite easily implement "logout from all devices", in exactly the way that you described.

    If you have to stick to access and refresh tokens, then the described solution is fine. Another one that you might try is this. When the user clicks "logout from all devices" then you write to the Redis DB the user’s ID and a timestamp when the logout occurred. Then, whenever an access or refresh token is used, you check whether it was issued before that timestamp. If so, you reject that token. In this solution, you need only one Redis entry per user, regardless of the number of issued tokens. You can safely clear the entry from Redis once you know that all tokens issued before that timestamp will be expired anyway.

    Login or Signup to reply.
  2. can you please brief more about logout from all devices…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search