Tokens on a phone
Two tokens, one vault, and a refresh nobody should notice. Watch them travel between the phone, SecureStore and the API, then break it: three screens at once, a stolen token, a sign-out.
What you'll take away
- Explain why a short access token pairs with a long refresh token, not one long token
- Refresh quietly on a 401, one refresh at a time while the other calls wait for it
- Know how rotation catches a stolen refresh token, at the price of one sign-in
- Sign out on the server first, then on the phone, so a leaked copy dies too
The 1-minute version
Tap a point and the picture below plays that step.
Press Sign in on the phone, then "16 minutes later" before opening Home. Try both ways and see which one signs people out, then let someone copy the refresh token
One screen fires 3 requests at once after the access token expired. All three get 401 and each refreshes on its own. What happens (the server rotates refresh tokens and catches reuse)?
The picture: the big phone shows the shop app as its user sees it. Beside it the Keychain vault holds the two tokens (gold for access, blue for refresh, grey once expired or used, red once revoked), the API tower keeps the refresh family on its roof, and the clock counts minutes since sign-in. Requests are lights on the street. 15 minutes and 30 days are examples, and every answer comes from a small model server.
Compare them all: Tokens on a phone
The same app holds its tokens four ways and meets four troubles in a row: the access token expires, three requests get 401 at once, someone reads the app's files, and a token leaks through a log. ✓ means the user stays in and nobody else keeps a working token for long.
Use it when Nowhere: it's here to show where it breaks
Skip it when Every app: the tokens are plain text, and parallel refreshes sign people out
A model: 15 minutes and 30 days are examples, not rules. Colliding refreshes sign people out on a server that rotates refresh tokens and catches reuse, which is what a server should do. Press any tile to see it large above, with when it fits.
Two tokens, two jobs
| Access token | Refresh token | |
|---|---|---|
| lives | minutes | days to weeks |
| goes to | every API call (Authorization: Bearer) | the token endpoint only |
| kept in | SecureStore (or memory) | SecureStore |
| if it leaks | works until it expires | rotation catches the reuse |
One refresh at a time
When several calls get 401 together, the first starts the refresh and the rest wait for the same promise. Sending the same refresh token three times looks exactly like theft to a server that rotates them, and it should revoke everything.
Tokens and cookies
A browser keeps a session in a cookie it guards itself (HttpOnly, SameSite). A native app has no such jar, so it sends a token in a header and guards it itself, in the Keychain or Keystore.
In real code
// A token client for the app: Bearer on every call, a silent refresh on 401, and ONE refresh at a time.
// Plain TypeScript: where the tokens are kept (SecureStore) and how bytes travel (fetch) are passed in.
export interface Tokens { access: string; refresh: string }
export interface TokenStore {
get(): Promise<Tokens | null>;
set(tokens: Tokens): Promise<void>;
clear(): Promise<void>;
}
export interface Reply { status: number; json(): Promise<unknown> }
export type Send = (path: string, init: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<Reply>;
export function createAuthClient(send: Send, store: TokenStore, onSignedOut: () => void) {
let refreshing: Promise<Tokens | null> | null = null;
// Every 401 that arrives while a refresh is running waits for that same refresh.
function refresh(): Promise<Tokens | null> {
refreshing ??= (async () => {
const old = await store.get();
if (!old) return null;
const res = await send("/token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refresh_token: old.refresh }) });
if (res.status !== 200) {
await store.clear();
onSignedOut();
return null;
}
const next = (await res.json()) as Tokens;
await store.set(next); // the server rotated it: the old refresh token is dead now
return next;
})().finally(() => {
refreshing = null;
});
return refreshing;
}
async function api(path: string): Promise<Reply> {
const tokens = await store.get();
if (!tokens) throw new Error("signed out");
const call = (access: string) => send(path, { headers: { authorization: `Bearer ${access}` } });
const res = await call(tokens.access);
if (res.status !== 401) return res;
const fresh = await refresh();
if (!fresh) throw new Error("signed out");
return call(fresh.access);
}
async function signOut(): Promise<void> {
const tokens = await store.get();
// Revoke on the server first, so a copy that leaked earlier dies too; then forget them here.
if (tokens) await send("/logout", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refresh_token: tokens.refresh }) });
await store.clear();
onSignedOut();
}
return { api, refresh, signOut };
}
tsc with the app's code, then really called by its Jest tests (in Node, not on a phone)Bearer on every call, a silent refresh on 401, and one shared refresh while it runs. Plain TypeScript: SecureStore and fetch are passed in.
Common questions
Where do I keep tokens on a phone?
In SecureStore (expo-secure-store) or react-native-keychain, which use the Keychain on iOS and the Keystore on Android. Never AsyncStorage: it's plain text in the app's files.
Why two tokens? Can't I use one long-lived token?
The access token rides on every request, so it can leak many ways; a short life means a leaked one works for minutes. The refresh token goes to one place and rotates on each use. A single month-long token, once leaked, works for the whole month.
Why do users sometimes get signed out for no reason?
A common cause: several requests get 401 at once and each refreshes with the same token. A server that rotates refresh tokens sees a used one come back and revokes the family. Fix it with one refresh at a time.
What does refresh token rotation buy me?
Each refresh token works once. If someone steals one and uses it, one side will present a used token, the server notices at once and revokes the family: the thief's tokens die too, at the price of one sign-in.
Is deleting the tokens on the phone enough to sign out?
No: a copy that leaked earlier still works. Ask the server to revoke the refresh token, then delete them on the phone. The old access token keeps working until it expires, unless the server checks a revocation list.
Why do mobile apps use tokens instead of cookies?
A native app has no browser cookie jar or its rules (SameSite, HttpOnly); a token in a header is simpler. But keeping it safe becomes the app's job. For the web side, see the Cookies and sessions lesson.
Next lesson
Cookies and sessionsLevel: Intermediate
A phone app guards its tokens itself; next, the web side: a login kept in a cookie, and the flags that keep it from being stolen.