Identity & access

Choose your integration shape

Five ways to hold a Versified session — server-side BFF, browser-only, native, edge gateway and service client — with the real cost of each.

Versified does not prescribe one architecture. It prescribes what a credential must prove — a signature, the issuer, one audience, an unexpired clock — and then leaves the shape of your session to you. Five shapes cover almost every honest integration. Each puts the token somewhere different, and each pays for that choice somewhere else.

The platform's own apps do not agree either

App Center web, Retill web and OneKitchen web run a server-side BFF. Retill Mobile is a public PKCE client with a device vault. Every backend is a service client. That is four of the five shapes below, in production today, served by one provider.

The constraint that shapes every choice

One fact removes some designs on day one: the token endpoint is not a browser endpoint. The provider is mounted before the API's CORS middleware and is configured with clientBasedCORS: () => false, so it answers no Access-Control-Allow-Origin. A page on your origin can send the person to /oidc/auth — that is a top-level navigation — but it cannot read a token response, and it cannot refresh. Anything that needs tokens has to be either on the issuer's origin or behind a server you run.

What that rules out

A single-page app on your own domain cannot complete the exchange today. The POST is a simple request, so it leaves before CORS is consulted: the code is spent at the provider and the browser then refuses to hand you the response. The result looks random rather than structural. Shape B sets out the three ways forward, and why only one of them is still a browser-only shape.

The five shapes at a glance

A · Server-side BFF
Client profileconfidential_web
Where tokens liveEncrypted in a server-side session store
Choose it whenThe app is server-rendered, or anything needs to survive a reload
B · Browser-only
Client profilepublic_pkce
Where tokens livePage memory, or localStorage if you must
Choose it whenIt is served from the issuer's origin — and almost nothing else
C · Native or desktop
Client profilepublic_pkce
Where tokens liveThe OS keystore (Keychain, Keystore)
Choose it whenYou ship an installed binary
D · Edge gateway
Client profileconfidential_web
Where tokens liveThe proxy's session store
Choose it whenYou already terminate traffic at an ingress
E · Machine-to-machine
Client profileconfidential_service
Where tokens liveNowhere — there is no session
Choose it whenNo person is involved at all

Shape A — Server-side BFF

Your server is the OAuth client. The browser sees an opaque session cookie and nothing else; every API call is made by the server, which attaches the bearer token. This is the shape both first-party web frontends use, and the one this documentation's examples assume.

  1. 1Register a confidential_web client with an HTTPS redirect such as https://app.example.com/api/auth/callback, and list the resources you need.
  2. 2Generate the PKCE verifier, state and nonce on the server; keep them against the browser session, never in the page.
  3. 3On the callback, exchange the code at /oidc/token with the verifier and the client secret, then verify the ID token (iss, aud, exp, nonce).
  4. 4Seal the tokens into a server-side store and set an HttpOnly, Secure, SameSite=Lax cookie holding only an opaque session id.
  5. 5Proxy every API call through your server, injecting Authorization from the session row. Refresh single-flight, under a row lock if you run more than one instance.
  6. 6Sign out by revoking the refresh token, deleting the row, then sending the browser to /oidc/session/end.
app/api/auth/callback/route.ts
const { code, state } = new URL(request.url).searchParams;
if (state !== storedState) return new Response(null, { status: 400 });

const res = await fetch(`${issuer}/token`, {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code: code!,
    redirect_uri: redirectUri,
    code_verifier: verifier,        // PKCE is required even for a confidential client
    client_id: clientId,
    client_secret: clientSecret,    // the whole point of Shape A
  }),
});

const tokens = await res.json();
const sessionId = await store.create({
  sealed: seal(tokens),             // AES-GCM, key from the environment
  expiresAt: Date.now() + tokens.expires_in * 1000,
});

return new Response(null, {
  status: 302,
  headers: {
    location: returnTo,
    "set-cookie": sessionCookie(sessionId), // opaque, HttpOnly, Secure
  },
});

The secret never leaves the server, and neither does the refresh token.

app/api/proxy/route.ts
// Every browser call hops through you. Identity comes from the row, not the page.
const { accessToken } = await session(request, { singleFlightRefresh: true });

return fetch(`${upstream}${path}`, {
  method: request.method,
  headers: {
    authorization: `Bearer ${accessToken}`,
    "content-type": request.headers.get("content-type") ?? "application/json",
  },
  body: request.method === "GET" ? undefined : request.body,
  duplex: "half",                   // stream both ways; never buffer a 50 MB body
});
The refresh token never touches the browser, so XSS cannot steal a long-lived credential
CostsYou operate a session store — a table or Redis, a TTL sweep and a cleanup job
Refreshes are serialized server-side, so rotation and reuse detection cannot race across tabs or instances
CostsEvery request gains one hop, and you must stream binary responses rather than buffer them
Sign-out is instant and total: delete the row
CostsExpiry, rotation, revocation and cookie policy are all yours to implement correctly
The page can be server-rendered with the session already resolved
CostsBrowser code can no longer call the API directly; every call needs a route
CSRF becomes one Origin check on one route, not a token dance in the page
CostsAn allowlist, a timeout and a header filter have to be kept correct forever

Choose it when the app is server-rendered, when a refresh token has to outlive a tab, or when you would rather own a database row than an XSS blast radius. Read Sign in from a web app for the flow, and Sessions, logout and revocation for the lifecycle.

Shape B — Browser-only single-page app

A static bundle that talks to the provider directly. It is the cheapest thing to deploy and the only shape where the rotating refresh token is reachable by page JavaScript — which is why the honest answer is usually not this shape, and why the platform has not enabled it.

  • Register public_pkce: no secret, token_endpoint_auth_method: none, and an HTTPS redirect that is not a loopback host.
  • Generate the verifier in the page and keep it in memory or sessionStorage for the round trip.
  • Send the browser to /oidc/auth, then verify state and nonce on the callback.
  • Then stop: the exchange at /oidc/token is cross-origin and the provider sends no CORS headers.
sign-in.ts (the half that works)
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = base64url(
  new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))),
);
sessionStorage.setItem("pkce", verifier);

location.assign(`${issuer}/auth?${new URLSearchParams({
  response_type: "code",
  client_id: clientId,
  redirect_uri: location.origin + "/callback",
  scope: "openid profile email offline_access",
  code_challenge: challenge,
  code_challenge_method: "S256",
  state,
  nonce,
})}`);

// On /callback, the fetch to /oidc/token is refused by the browser:
// no Access-Control-Allow-Origin comes back, and the code is spent anyway.

There are exactly three ways forward, and only the first is a genuine Shape B:

  1. 1Serve the page from the issuer's origin. The token endpoint is then same-origin and no CORS applies. Practical only for the platform itself, not for a third-party app on its own domain.
  2. 2Add a same-origin token endpoint of your own. It holds the code exchange and the refresh, and keeps the refresh token out of the page. That is Shape A with a smaller surface — most of the cost, none of the ambiguity.
  3. 3Ask the platform to enable client CORS. Not available today. It would put rotating refresh tokens into page JavaScript, make reuse detection a per-tab problem, and turn any XSS into an account takeover.
No server to operate: a static bundle on any CDN
CostsTokens live exactly where XSS lives
Nothing to provision but a bucket
CostsA refresh token readable by page JavaScript is an account-takeover primitive
Debugging is the network tab, end to end
CostsRotation plus N tabs is a refresh race you have to serialize in the page
Deploys are instant and reversible
CostsEvery API call is cross-origin: preflight on the API, and the API origin becomes public
Fastest possible first integration when the origin matches
CostsNo server-side revocation: a signed-out session lives until the token expires

Choose it when the page is served from the issuer's origin, or when you accept option 2 and call it what it is. Do not choose it because it is the least code today — the refresh token is the part you cannot undo later.

Shape C — Native or desktop application

An installed app is a public client, and it is the shape the token endpoint was designed for: there is no browser CORS in the way, and the operating system provides a vault the page has no equivalent of. The app opens the system browser, receives a deep link, exchanges the code itself and stores the refresh token in the keystore.

  • Register public_pkce. The provider treats it as application_type: native, so custom schemes are legal — com.acme.app://auth/callback — and https on a loopback host is refused on purpose.
  • Up to 10 redirect URIs, exact match, no wildcards, fragments or whitespace. Plain http is accepted only for a loopback host.
  • Open the system browser, never an embedded webview: the provider renders its own sign-in, second factor and consent pages.
  • Keep the refresh token in the Keychain or Keystore; keep the access token in memory and re-mint it on cold start.
  • Queue refreshes rather than de-duplicating them — the provider rotates the token on every use, so a second concurrent grant presents a spent token.
exchange.ts (public client)
const res = await fetch(`${issuer}/token`, {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code,
    redirect_uri: "com.acme.app://auth/callback",
    code_verifier: verifier,
    client_id: clientId,      // token_endpoint_auth_method: none — there is no secret
  }),
});

const tokens = await res.json();
await SecureStore.setItemAsync("refresh_token", tokens.refresh_token);
// access_token stays in memory; refresh before `expires_in` runs out.
No secret to leak, and no CORS to negotiate
CostsA stolen or rooted device is a stolen session until you revoke it
The refresh token sits in a hardware-backed vault
CostsCustom scheme callbacks can be claimed by another app; prefer universal links when you own a domain
Works offline: the session survives a restart
CostsRefresh serialization has to be re-implemented per platform
One client id serves iOS, Android and desktop
CostsOne device holding a stale token can invalidate the whole grant
Revocation is a single call to /token/revocation
CostsUpdate cadence: a client id change means a store release, not a deploy

Choose it when you ship an installed binary. Read Sign in from a mobile app for the framework-level flow, deep-link rules and the two-audience pattern.

Shape D — Edge gateway or reverse proxy

Same architecture as Shape A, with the code living in infrastructure instead of your application: an OIDC-aware proxy (oauth2-proxy, Envoy with ext_authz, nginx auth_request) owns the flow, the cookie and the refresh, and injects Authorization into whatever it forwards.

  1. 1Register a confidential_web client whose redirect is the proxy's callback — /oauth2/callback by convention.
  2. 2Point the proxy at the issuer and give it a shared session store (Redis), because a cookie-only store cannot serialize refresh across replicas.
  3. 3Let the proxy forward Authorization upstream, and terminate the session at /oauth2/sign_out plus the provider's /session/end.
  4. 4Keep the audience check, the tenant check and the JSON envelope in your API. The proxy authenticates; it does not authorise.
gateway (illustrative flags)
oauth2-proxy \
  --provider=oidc \
  --oidc-issuer-url=https://apps-api.versified.com.gh/oidc \
  --client-id=ledgerly-web \
  --client-secret=$CLIENT_SECRET \
  --redirect-url=https://app.ledgerly.com/oauth2/callback \
  --session-store-type=redis --redis-connection-url=redis://cache:6379 \
  --cookie-secure=true --pass-access-token=true \
  --scope="openid profile email offline_access"

The exact flags differ per proxy; the shape does not.

No bespoke auth code inside the application
CostsA second deployable plus its configuration now sits on the critical path
One gate shared by every service behind the ingress
CostsThe failure mode is opaque — a redirect loop or a missing header, not a stack trace
Session, refresh and cookie policy handled by a maintained component
CostsPer-audience token caching and tenant headers usually need custom extension anyway
One place to audit, rate-limit and rotate the client secret
CostsThe proxy must scale with your traffic, and its session store becomes stateful infrastructure
Your app stays framework-agnostic: any language, any runtime
CostsLocal development needs the proxy too, or a second code path nobody tests

Choose it when you already run an ingress, several services share one sign-in, or you want no auth code in the application at all. Keep this page's Shape A checklist next to it: the obligations do not move, only the implementation does.

Shape E — Machine-to-machine

No person, no consent screen, no session. A confidential_service client mints a token with client_credentials for one audience and calls the Application API. This is not an alternative to the shapes above — it is what your backend uses *alongside* one of them.

POST {issuer}/token
POST /oidc/token HTTP/1.1
Host: apps-api.versified.com.gh
Content-Type: application/x-www-form-urlencoded
Authorization: Basic base64(client_id:client_secret)

grant_type=client_credentials
&scope=appcenter:service
&resource=urn:versified:api:appcenter
  • Cache the token until 60 seconds before expires_in; there is no refresh grant and no ID token.
  • The response has no person in it. A service token is accepted only on /appcenter/v3/app/*; a user token there is refused with 403 service_token_required.
  • One audience per token, as everywhere else. Two APIs means two tokens — or two clients.
  • The rate limit is per client id, 600 requests per minute, so one runaway job starves every process sharing the client.
No person, no consent, no redirect URI to keep in sync
CostsThere is no per-user authorisation: the client can do anything the app-scoped API allows
One credential per service, rotatable on its own schedule
CostsThe secret has to exist in every environment that runs the service
Predictable, inspectable rate limit per client
CostsOne noisy job starves everything sharing that client id
The token can be cached for its whole lifetime
CostsA leaked secret is a compromised application until you rotate it
The simplest thing on this page to implement
CostsIt cannot stand in for a user session — no sub, no tenant, no consent

Choose it when a job, a sync or a webhook replay needs to read or write App Center data. Read Service tokens for rotation, caching and the route allow-list.

Side by side

Profile
A · BFFconfidential_web
B · Browserpublic_pkce
C · Nativepublic_pkce
D · Gatewayconfidential_web
E · Serviceconfidential_service
Refresh token lives
A · BFFYour session store
B · BrowserPage memory — and unreachable today
C · NativeOS keystore
D · GatewayThe proxy's store
E · ServiceNone
Sign-out
A · BFFDelete row, revoke, end session
B · BrowserDelete from memory; revoke cannot be reached
C · NativeRevoke, then clear the vault
D · GatewayProxy sign-out plus end session
E · ServiceNot applicable
You operate
A · BFFSession store, proxy route
B · BrowserA static host
C · NativeThe app build and update channel
D · GatewayAn ingress and its session store
E · ServiceA secret and a token cache
Best fit
A · BFFServer-rendered web
B · BrowserSame-origin pages only
C · NativeInstalled apps
D · GatewayMany services, one gate
E · ServiceBackends and jobs

You can mix shapes

Shapes are chosen per surface, not per company. A product with a dashboard, a mobile app and a backend uses three of them at once, and they all resolve to the same sub.

App Center web
ShapeA · BFF
WhySession survives reloads; refresh never reaches the page
Retill web
ShapeA · BFF
WhySame client rules, different client id and audience
OneKitchen web
ShapeA · BFF
WhyOne audience, one upstream
Retill Mobile
ShapeC · Native
WhyNo secret, vault storage, offline tolerance
Every backend
ShapeE · Service
WhyCapabilities and the Application API, with no person involved

The one thing that must not vary is what a request proves. Whatever holds the token, the API still verifies the signature, the issuer and its own audience, then resolves the person from sub and the membership from its own tables.

Deciding in one pass

  • No person signs in — a job, a sync, a webhook replay: Shape E.
  • You ship an installed app: Shape C.
  • The app is server-rendered, or a session must outlive a tab: Shape A.
  • You already terminate traffic at an ingress and want no auth code: Shape D.
  • A static SPA on your own domain: Shape A with the smallest possible surface. The browser-only shape cannot read a token response.
  • Two audiences for one person: name both resources on the authorization request, then mint one token per resource. RFC 8707 allows one resource indicator per token request.

What every shape still owes

  • Verify the access token: signature against the JWKS, iss, and your own aud.
  • Resolve the person from sub, then the membership and privilege from your own data. The token proves who, never what.
  • Revoke on sign-out: a deleted session is not a revoked grant.
  • Treat invalid_grant on refresh as terminal, and a network failure as retryable — they look alike and mean opposite things.
  • Never log a token, and never forward a cookie upstream.

The shape changes where the token lives, not what it proves

Every rule in Tokens and claims applies to all five shapes. Choosing a shape decides your operations budget and your blast radius — not the verification you owe the platform.

Something here out of date or unclear?

The platform team answers integration questions directly.

support@versified.com.gh
32 pages in this documentation