Home > database >  How to manage multi-device simultaneous login with JWT tokens?
How to manage multi-device simultaneous login with JWT tokens?

Time:06-09

My query is regarding supporting multi-device login for the same user at the same time using JWT tokens. I am using NestJS as my backend.

User table: userid, username, password(contains hashed password), name, refreshToken(contains hashed refresh token)

When the user does a /api/login call, on having a valid username and password, the access token and refresh token are generated using jwt passport library. The refresh token is hashed and stored in the refresh column of the user table for that particular user and the access token and the refresh token are sent to the client through the response.

During the /api/refresh call, the refresh token sent by the user is validated with the hashed refresh token that is present in the user table for that user and then, a new access token and a new refresh token are generated. The new refresh token is hashed and updated in the user table refreshToken column for that same user row.

This flow works perfectly for a user logged in with a single device. When the same user gets logged in using multiple devices at the same time, during login, the refresh token is updated in the refreshToken column of the user table for the same user row, which makes us lose an existing/valid refresh token for the same user.

Flow:

  1. user 1 logs in using device 1 --> refreshToken column for user 1 is updated with a new refresh token
  2. user 1 logs in using device 2 --> refreshToken column for user 1 is overwritten with a new refresh token and we lose the refresh token that was created for device 1

I would like to know what would be the best industrial practice to manage the JWT refresh flow for a user logged in with multiple devices at the same time?

CodePudding user response:

The simplest way would be to keep the refresh tokens in a separate table. Usually, refresh tokens are kept separately from the user's account data, as the user can have more refresh tokens active at any given time. Whenever a refresh token is used you can find the concrete token and create a new one in its place.

By the way, there is no need to hash the refresh tokens kept in your database. They are unique to your system, they're not passwords.

  • Related