Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh tokens on multiple devices

I have an Api and a mobile client. I am using refresh tokens as following:

  1. User provides credentials, Api returns back an access token and a refresh token. The refresh token is then saved with its expiration dateTime in users table in the DB.
  2. Client consumes some protected resources using the given access token.
  3. Access token expires, so the client provides his refresh token and gets new pair of tokens.
  4. Step 2 and 3 repeats over and over.

Problem: Let's say user has 2 devices, A and B. He successfully logged in using device A, so he got 2 tokens and he is happy. As soon as the user logs in from device B, the Api will send him new pair of tokens, which mean the new refresh token will override the already given one to device A. Now user goes back to device A aaaand it's gone (invalid refresh token!) so he has to provide credentials again, which I, the user and you don't want to.

Suggestions: I have found 2 approaches to solve the problem, but because I am pretty new to this topic I can't see which is best practice:

Approach A: Save multiple refresh tokens per user, and saving a device identifier (still no idea what exactly in case of different client types like mobile, browser and desktop client!) but anyway. In this approach when a user logs in from device A, the Api provides both tokens. User logs in from device B, the Api delivers new pair of tokens. He goes back to device A, he uses his first token again (still valid).

Approach B: Keep 1 refresh token per user. when user logs in from device B, Api sends back the only refresh token (I should not care about the devices as long as the user provides valid credentials, right?)

Could you point out the pros and cons for each approach?

like image 953
Karro Avatar asked Sep 13 '25 13:09

Karro


1 Answers

Approach A is the normal way to handle this. Access/refresh tokens should not be shared accross different sessions/devices.

Each should get their own pair. When you use the refresh_token operation, it should only expire the refresh token that was used with that request, and not any unrelated ones.

like image 80
Evert Avatar answered Sep 15 '25 14:09

Evert