Web Development Bug Report

Refresh token rotation logged users out whenever two tabs refreshed at once

After enabling refresh token rotation with reuse detection, users with several tabs open were randomly signed out. Two tabs refreshed with the same token, the server saw reuse and revoked the whole token family. The fix was a single-flight refresh in the client and a short grace window on the server.

Amara Nwosu Amara Nwosu @amaranwosu · November 21, 2026 · 8 min read · 85 Views
Banner: two browser tabs racing to refresh the same token

We moved our web app from long-lived refresh tokens to rotating ones: every refresh returns a new refresh token and invalidates the old one. We also enabled reuse detection. If an old refresh token is ever presented again, the server assumes it was stolen and revokes every token issued from the same login, the "token family". Both are recommended practice for browser clients.

Within a day, complaints arrived: "I keep getting logged out", mostly from people who work with many tabs open, such as dispatchers watching several screens. Our session dashboard showed reuse detection firing around 900 times a day, almost always within one second of a legitimate refresh, from the same IP and user agent.

A real token thief does not usually replay a token within the same second, from the same browser. This looked like our own client.

Reproducing

Access tokens lived 5 minutes. Each tab held its own copy of the auth state in memory, loaded from localStorage on start, and refreshed when its access token expired. We opened two tabs, waited for the access token to expire, and triggered a request in both at the same moment. The server log:

10:00:00.104 POST /oauth/token grant=refresh_token rt=fam_81c..#14  -> 200, issued #15
10:00:00.131 POST /oauth/token grant=refresh_token rt=fam_81c..#14  -> 400 invalid_grant
             reuse detected for family fam_81c (token #14 already rotated), revoking family
10:00:02.660 GET /api/shipments  access=...#15  -> 401 token revoked

Both tabs read refresh token #14 from storage. Tab A refreshed first and got #15. Tab B sent #14 27 milliseconds later. To the server, #14 had already been used, so this was reuse, and it revoked the whole family, including the brand-new #15 that tab A had just received. Both tabs were signed out.

Why rotation plus reuse detection exists

A refresh token in a browser can leak: an XSS bug, a malicious extension, a compromised device. With a long-lived, non-rotating refresh token, the attacker can mint access tokens for as long as it is valid. Rotation limits the value of a stolen token: once either party uses it, the other's copy is dead. Reuse detection turns that into an alarm: if both the attacker and the user try to use the same token, one of them is reusing, and the server cannot tell which, so it ends the session for both.

The OAuth 2.0 Security Best Current Practice (RFC 9700) describes this approach for public clients, and the guidance for browser-based apps recommends rotating refresh tokens for single-page applications.

Why our client tripped it

The rotation design assumes the client uses each refresh token once. Our client was really several independent clients sharing one token through localStorage:

  • Each tab decided on its own when to refresh.
  • They read the same refresh token from storage.
  • Nothing coordinated them, so near-simultaneous refreshes were normal, not rare.

It got worse with retries. Our HTTP wrapper retried a refresh on network timeout. On a slow mobile connection the first request sometimes reached the server and succeeded, but the response was lost; the retry then presented the same, now-rotated token, and reuse detection fired. Same effect, one tab.

Environment

Item Value
Client React single-page app, tokens in localStorage, 2 to 15 tabs per user typical
Auth server in-house OAuth 2.0 server, rotation + family revocation
Token lifetimes access 5 min, refresh 14 days sliding
Symptom about 900 family revocations per day, 95% within 1 s of a legitimate refresh

We fixed it on both sides. The client should not race, and the server should tolerate the narrow cases where a legitimate client still does.

1. Client: single-flight refresh, across tabs

Within one tab, concurrent requests that see an expired token must share one refresh call:

let inflight = null;

async function refreshOnce() {
  if (!inflight) {
    inflight = doRefresh().finally(() => { inflight = null; });
  }
  return inflight;
}

Across tabs, we use the Web Locks API so only one tab refreshes at a time, and the others pick up the result from storage instead of refreshing themselves:

async function getAccessToken() {
  const current = readTokens();
  if (!isExpiringSoon(current.accessToken)) return current.accessToken;

  return navigator.locks.request("auth-refresh", async () => {
    const latest = readTokens();               // another tab may have refreshed while we waited
    if (!isExpiringSoon(latest.accessToken)) return latest.accessToken;

    const fresh = await refreshOnce(latest.refreshToken);
    writeTokens(fresh);                        // other tabs see this via the storage event
    return fresh.accessToken;
  });
}

window.addEventListener("storage", (e) => {
  if (e.key === "auth") reloadTokensFromStorage();
});

The re-read inside the lock is the important line. A tab that waited for the lock usually finds a fresh token already written by the tab that held it, and makes no network call at all.

We also removed automatic retries of refresh requests. A failed refresh now waits for the next user action and tries once, with the latest token from storage.

2. Server: a short grace window for the immediately previous token

Even with a careful client, a lost response can lead to a legitimate repeat. Several identity providers handle this with a short, configurable leeway in which the previous refresh token is still honoured, and we adopted the same idea with tight conditions. Our rule:

  • When refresh token N is rotated to N+1, record the time and keep N as "recently rotated".
  • If N is presented again within 10 seconds and N+1 has not yet been used, return the same N+1 (and a new access token) instead of treating it as reuse.
  • Outside those conditions, it is reuse: revoke the family as before.
def refresh(presented: str, client: Client) -> TokenPair:
    token = store.get(presented)
    if token is None or token.revoked:
        raise InvalidGrant()

    if token.rotated_at is None:
        return rotate(token)

    successor = store.get(token.successor_id)
    within_grace = now() - token.rotated_at <= timedelta(seconds=10)
    if within_grace and successor and successor.used_at is None and same_client(token, client):
        return reissue(successor)          # same refresh token N+1, new access token

    store.revoke_family(token.family_id, reason="refresh_token_reuse")
    raise InvalidGrant()

The successor-not-yet-used condition keeps the security property: if an attacker and a user both hold N, and one of them has already moved on to N+1, any later use of N is still detected. The window is short enough that a thief replaying a stolen token minutes later gets nothing.

3. Keep refresh tokens out of JavaScript where possible

The longer-term change, now in progress, is to move token handling into a backend-for-frontend: the browser holds an HttpOnly, Secure, SameSite=Strict session cookie, and our server does the refresh. That removes the token from reach of XSS entirely, and the multi-tab race becomes a server-side concern that a single lock solves. The guidance for browser-based OAuth apps describes this pattern as the most secure option for SPAs.

1. A multi-tab test in the browser test suite. Playwright opens three pages in the same context, expires the access token, and fires a request in each at the same time:

test("parallel tabs refresh once and stay logged in", async ({ context }) => {
  const pages = await Promise.all([1, 2, 3].map(() => context.newPage()));
  await Promise.all(pages.map((p) => p.goto("/app")));
  await expireAccessToken(context);

  await Promise.all(pages.map((p) => p.click("text=Refresh list")));

  for (const p of pages) await expect(p.locator("text=Shipments")).toBeVisible();
  expect(await countServerRefreshes()).toBe(1);
});

Before the fix: three refresh calls, two reuse detections, all three pages on the login screen. After: one refresh call, all three pages logged in.

2. Server unit tests for the grace window, including the cases that must still revoke: replay after 11 seconds, replay after the successor was used, and replay from a different client ID.

3. Production metrics. Family revocations dropped from about 900 per day to about 6. We review those manually for a while; so far each has been an old token presented hours later, which is exactly what reuse detection is for.

4. Security implications. We considered and rejected two easier fixes. Turning off reuse detection would have stopped the logouts and removed our only signal of token theft. A long grace window (minutes) would have done almost the same. The narrow window with the successor-unused condition keeps detection for every realistic theft scenario while tolerating our own clients.

Takeaways

  • Rotating refresh tokens assume each token is used once. Multiple tabs and retries break that unless the client coordinates.
  • Make refresh single-flight within a tab and across tabs (Web Locks plus a re-read inside the lock).
  • A short server-side grace window, only while the successor is unused, tolerates lost responses without weakening reuse detection.
  • Where you can, keep tokens out of the browser with a backend-for-frontend.

References: RFC 9700, OAuth 2.0 Security Best Current Practice, OAuth 2.0 for Browser-Based Applications, Web Locks API on MDN, RFC 6749, OAuth 2.0.

Add a label

#authentication #oauth2 #race-condition #refresh-tokens #token-rotation
Written by
Amara Nwosu @amaranwosu

I build and maintain public and partner APIs, currently for a logistics platform with web, mobile and third-party clients all calling the same endpoints. Before that I worked on identity: login, sessions, OAuth integrations and the long tail of edge cases they create. The bugs I care about sit at the contract between client and server. A PUT that wiped fields the client never sent, a cache that served one user's page to another, a field removal that broke app versions still in the wild, a refresh flow that logged people out when two tabs raced. None of these show up in a happy-path demo. My posts walk through how each one surfaced, what the HTTP or auth spec actually says, the fix we shipped and the tests we added so the next change to the API does not repeat it.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.