React

Sign users in from a single-page React application with no backend, as a public client using PKCE.

This guide is for a React single-page application with no server of its own. The application is a public client: it has no client secret, and PKCE protects the exchange. If your application has a server, do the exchange there instead. See Next.js or Python.

Set up the application

On your application's OAuth2 tab:

  1. Turn on Public Client.
  2. Add the redirect URI, for example http://localhost:5173/callback.
  3. Add your application's origin to Allowed Origins, for example http://localhost:5173. The browser needs it to read the token response. http is allowed only for loopback addresses; use https in production.

A public client must not send a client_secret. See Token exchange.

PKCE and state in the browser

The verifier and state must survive the redirect to onefold and back, so keep them in sessionStorage, which is scoped to the tab.

src/auth.ts
const ISSUER = "https://onefold.eitozx.com";
const CLIENT_ID = "your-client-id";
const REDIRECT_URI = `${window.location.origin}/callback`;

function base64url(bytes: Uint8Array): string {
  return btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

function randomValue(): string {
  return base64url(crypto.getRandomValues(new Uint8Array(32)));
}

async function challengeFor(verifier: string): Promise<string> {
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
  return base64url(new Uint8Array(digest));
}

export async function signIn() {
  const verifier = randomValue();
  const state = randomValue();
  const nonce = randomValue();
  sessionStorage.setItem("onefold_auth", JSON.stringify({ verifier, state, nonce }));

  const url = new URL(`${ISSUER}/o/authorize/`);
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    scope: "openid identity",
    state,
    nonce,
    code_challenge: await challengeFor(verifier),
    code_challenge_method: "S256",
  }).toString();
  window.location.assign(url);
}

Exchange the code on the callback page

src/auth.ts
function decodeJwtPayload(jwt: string) {
  const base64 = jwt.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
  const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
  return JSON.parse(new TextDecoder().decode(bytes)); // UTF-8 safe
}

export async function completeSignIn(search: string) {
  const params = new URLSearchParams(search);
  const saved = JSON.parse(sessionStorage.getItem("onefold_auth") ?? "null");
  sessionStorage.removeItem("onefold_auth");

  if (params.get("error")) throw new Error(params.get("error")!);
  if (!saved || params.get("state") !== saved.state) throw new Error("Invalid sign-in state");

  const response = await fetch(`${ISSUER}/o/token/`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: params.get("code") ?? "",
      redirect_uri: REDIRECT_URI,
      client_id: CLIENT_ID,
      code_verifier: saved.verifier,
    }),
  });
  if (!response.ok) throw new Error(`Token request failed: ${response.status}`);
  const tokens = await response.json();

  const claims = decodeJwtPayload(tokens.id_token);
  if (claims.iss !== ISSUER || claims.aud !== CLIENT_ID || claims.nonce !== saved.nonce) {
    throw new Error("Unexpected ID token");
  }
  return { tokens, user: { sub: claims.sub as string, email: claims.email as string | undefined } };
}

Call it from your /callback route, for example completeSignIn(window.location.search) in an effect, then navigate away so the code is not left in the address bar.

The ID token here came straight from the token endpoint over HTTPS, so the application checks its claims (iss, aud, nonce) without verifying the signature, as OpenID Connect Core §3.1.3.7 permits. Your own API must not trust claims sent up by the browser. It should verify the user itself. See Protect your API.

Keep tokens in memory

Hold the tokens in memory, for example in React state or a module variable, not in localStorage, where any script on the page can read them. The user signs in again after a full reload, or you refresh using the refresh token.

src/auth.ts
export async function refresh(refreshToken: string) {
  const response = await fetch(`${ISSUER}/o/token/`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: refreshToken,
      client_id: CLIENT_ID,
    }),
  });
  if (!response.ok) throw new Error("Refresh failed; sign in again");
  return response.json(); // contains a NEW refresh token; the old one is spent
}

Every refresh rotates the refresh token. If two tabs refresh with the same token more than 10 seconds apart, onefold treats the second as a stolen token and ends the session. Refresh from one place only. See Keep users signed in.

Signing out

Discard the tokens held in memory. This does not sign the user out of onefold.

Next

On this page