To authenticate users in my Angular app i use access tokens with expiry time X seconds and refresh tokens that can be used to prolong the auth for another X seconds.
So the flow is this:
- A user signs in. Both the access and refresh tokens are stored in local storage
- A timer is set (5% shorter than X seconds).
- When the timer is done, a refresh token request is sent to the server and the local storage is updated with the resulting (new) access and refresh tokens.
My problem is this:
- If I have multiple tabs open, I will inevitably end up in situations where the refresh is triggered from multiple tabs at the same time. The server will accept the first request, but throw a
400 Bad Request - Invalid refresh token
for the subsequent requests, since it considers them used.
Does anyone have a good idea how this could be solved? How does one synchronize things across tabs/windows? I have a couple of ideas but they all seem a bit far fetched:
- If the response is
400 Bad Request
, then retry in a little while (or check if there is a valid updated token already). - Try to synchronize the server requests across tabs by posting messages between them.