Skip to main content

Refresh tokens that rotate

Handle a refresh token that changes at each use, in one tab and in several, and recover when a refresh fails.

RecipeReadyView source
Works with
JavaScript / TypeScriptPlain HTTP

What it shows​

  1. A person signs in to a browser app. The app receives an access token and a refresh token.
  2. Two tabs need a new access token at the same moment. One tab sends the refresh request, and the other tab takes the result.
  3. The refresh returns a new refresh token. The old one stops working.
  4. Somebody uses the old refresh token again. LumoAuth refuses it and ends the whole sign-in.
  5. The next refresh of the app fails. The session ends in both tabs, and the app sends the person to sign-in.

Before you start​

  • An API key for the setup script, with the scopes admin:clients:read and admin:clients:write.
  • A public application with the refresh token grant. The setup script creates the application "Acme Notes".
  • A user of your organization to sign in with, and a browser.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
CLIENT_IDThe client ID of the application. The setup script prints it.
REDIRECT_URIOptional. Where LumoAuth sends the browser after sign-in. The default is http://localhost:3000/callback. Set it before the setup script too.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node oauth/refresh-token-rotation/setup.mjs
setup.mjs
// Creates what the recipe needs: a public application for a browser app,
// with the refresh token grant. Run it again at any time.
//
// node oauth/refresh-token-rotation/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
import { ensure, printEnv } from '../../_lib/admin.mjs';

// Where LumoAuth sends the browser after sign-in. The programs listen there.
const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';

const client = await ensure('/admin/clients', (c) => c.name === 'Acme Notes', {
name: 'Acme Notes',
// A browser app cannot keep a secret. It signs in with PKCE.
isConfidential: false,
// Without refresh_token in this list, the application gets no refresh tokens.
grantTypes: ['authorization_code', 'refresh_token'],
redirectUris: [redirectUri],
scopes: ['openid', 'profile', 'email'],
});

console.log('The application "Acme Notes" is ready.');
printEnv({ CLIENT_ID: client.clientId, REDIRECT_URI: redirectUri });

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Both programs print an address first and wait until you have signed in there. The Node.js version runs the session class of the browser package in Node.js, with two sessions that stand for two tabs. The curl version prints the answers of the server.

oauth/refresh-token-rotation/js/session.mjs
// Sign in once, then watch the refresh token rotate: one refresh for two
// tabs, an old refresh token that is refused, and a session that ends.
//
// node oauth/refresh-token-rotation/js/session.mjs
//
// The session class of @lumoauth/client is what a browser app uses. This
// program runs it in Node.js. Its two sessions stand for two tabs.
import http from 'node:http';
import { AuthModule, LumoAuthSession, memoryStorageAdapter } from '@lumoauth/client';

const redirectUri = process.env.REDIRECT_URI ?? 'http://localhost:3000/callback';

// Count the requests to the token endpoint, to see which tab refreshes.
let tokenRequests = 0;
const countingFetch = (url, init) => {
if (String(url).endsWith('/oauth/token')) tokenRequests++;
return fetch(url, init);
};
const auth = new AuthModule({
baseUrl: process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev',
orgId: process.env.LUMOAUTH_ORG_ID,
clientId: process.env.CLIENT_ID,
fetch: countingFetch,
});

// Two tabs of one browser share the storage. In a browser, pass
// localStorageAdapter() here; the tabs then also share a Web Lock.
const storage = memoryStorageAdapter();
const tabA = new LumoAuthSession({ auth, redirectUri, storage });
const tabB = new LumoAuthSession({ auth, redirectUri, storage });

// 1. Sign in with the authorization code flow, as the app does at its callback.
const { url, codeVerifier, state } = await tabA.buildAuthorizationUrl();
console.log(`Open this address in a browser and sign in:\n${url}\n`);
const code = await new Promise((resolve, reject) => {
const server = http.createServer((request, response) => {
const query = new URL(request.url, redirectUri).searchParams;
response.end('Signed in. You can close this tab.');
server.close();
query.get('state') === state && query.get('code') ? resolve(query.get('code')) : reject(new Error(`Unexpected callback: ${request.url}`));
});
server.listen(new URL(redirectUri).port);
});
const tokens = await auth.exchangeCodeForTokens({ code, codeVerifier, redirectUri });
console.log(`signed in: the access token is valid for ${tokens.expires_in} s`);

// A real session refreshes when the access token has less than 30 seconds
// left. To see that now, tell the session that the token ends in 20 seconds.
const almostExpired = (from) => tabA.adopt({ access_token: from.accessToken ?? from.access_token, refresh_token: from.refreshToken ?? from.refresh_token, expires_in: 20 });
const settle = () => new Promise((resolve) => setTimeout(resolve, 100)); // lets the tabs exchange their messages
await almostExpired(tokens);
await settle();

// 2. Both tabs need a token at the same moment. One tab asks the server,
// and the other tab takes the result.
tokenRequests = 0;
const [fromA, fromB] = await Promise.all([tabA.getToken(), tabB.getToken()]);
console.log(`two tabs refreshed: ${tokenRequests} request to the token endpoint, same token in both: ${fromA === fromB ? 'yes' : 'no'}`);

// 3. The refresh returned a new refresh token. The old one does not work again.
const current = tabA.getTokens();
console.log(`refresh token changed: ${current.refreshToken !== tokens.refresh_token ? 'yes' : 'no'}`);
try {
await auth.refreshToken(tokens.refresh_token);
console.log('old refresh token -> accepted');
} catch (error) {
console.log(`old refresh token -> refused (${error.code})`);
}

// 4. LumoAuth took the second use of the old token as a sign of theft and
// ended the whole sign-in. The next refresh of the app fails, the session
// ends, and the app sends the person to sign-in.
tabB.subscribe(() => {
const { isSignedIn, error } = tabB.getSnapshot();
if (!isSignedIn) console.log(`tab B: signed out (${error ?? 'the other tab signed out'}), go to sign-in`);
});
await almostExpired(current);
await settle();
console.log(`next refresh in tab A -> ${(await tabA.getToken()) ? 'a new token' : `signed out (${tabA.getSnapshot().error})`}`);
await settle();

tabA.dispose();
tabB.dispose();
node oauth/refresh-token-rotation/js/session.mjs

LumoAuthSession refreshes by itself, about one minute before the access token ends. Your app calls getToken() before each request to its API and subscribe() to learn that the session ended. The program cannot wait an hour for that, so it tells the session twice that the token ends in 20 seconds.

Check the result​

Output
signed in: the access token is valid for 3600 s
two tabs refreshed: 1 request to the token endpoint, same token in both: yes
refresh token changed: yes
old refresh token -> refused (invalid_grant)
next refresh in tab A -> signed out (refresh_failed)
tab B: signed out (the other tab signed out), go to sign-in
  • The second line is the reason for the Web Lock. Without it, each tab sends its own refresh request with the same refresh token, and the slower tab is refused.
  • The curl version shows the same rule without an SDK. The first refresh returns a new refresh token, and both later requests answer invalid_grant.
  • In a browser, pass localStorageAdapter() as the storage, so that the tabs share the tokens.

Limits​

  • The refresh tokens of a public application always rotate. A confidential application can keep one refresh token: in the portal, open the application, the Security tab, Token settings, and set Refresh token rotation to Keep the same token.
  • A refresh token is valid for 30 days unless the application sets another lifetime. The chain of refresh tokens of one sign-in ends after 90 days, or after the lifetime of the application if that is longer.
  • After the second use of an old refresh token, the app cannot recover the session. The person signs in again.
  • A failed refresh always ends the session, also when the cause is a network error. getSnapshot().error is refresh_failed in both cases.