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.

Level: DeepWatch: 17 steps · ~1½ minutesExpire, overlap, steal, sign outRecall: 3 questions · 8 cardsCompare 4 designsTypeScript · Jest

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.

4Compare them all
On a 401: one refresh at a timeaccess 15 min · refresh 30 d
API · no tokens yetno token
minute 0
Keychain / Keystore · empty
Shopmai@example.com••••••••Sign in
POST /login → …
Step 1 / 17 · step by step
0refreshes that worked
0answered 200
not yetstill signed in?

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.

Step 4 · Every option at once, on one clock

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.

Trouble 1 / 4: The access token expires mid-use
AsyncStorage + each call refreshesAsyncStorage.setItem("refresh", …)held 0 of 0

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 tokenRefresh token
livesminutesdays to weeks
goes toevery API call (Authorization: Bearer)the token endpoint only
kept inSecureStore (or memory)SecureStore
if it leaksworks until it expiresrotation 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

auth-client.ts
// 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 };
}
Run: 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.