Skip to Content
Otoko Identity

Mobile app

In the wizard: An API that Otoko Identity calls · Mobile app

A phone app, such as React Native (Expo) or Flutter, that signs people in on its own screens. Otoko Identity's (OI's) sign-in pages never show: the app sends what the person types to your backend, and your backend calls OI with the app's API key, which never leaves the server. Your backend gives the app an access token and a refresh token, checks the access token on every API call, and is also the backend OI calls, on every sign-in and when a session ends. The app needs no OI library.

What you'll build

  • The backend: sign-in, renewing tokens and sign-out; sign-up with a code OI emails; forgot password; a protected GET /api/me, which makes the person's user on their first request; and the three routes OI calls, /internal/v1/sign-in-check, /internal/v1/session-ends and the signed /internal/v1/account-created.
  • The mobile app: sign-in, sign-up, code and forgot-password screens, and a home screen that calls the API and signs out. The tokens go in the phone's secure storage, and the app renews the access token when it expires.
The personThe app calls your backendYour backend calls OI
Signs inPOST /mobile/sign-inPOST /internal/v1/sessions/password, then OI asks your sign-in-check
Is using the app, and the access token expiresPOST /mobile/refreshPOST /internal/v1/sessions/refreshes
Signs outPOST /mobile/sign-outPOST /internal/v1/sessions/sign-outs, then OI calls your session-ends
Signs upPOST /mobile/sign-upPOST /internal/v1/identities, then POST /internal/v1/identities/{id}/code
Asks for a new codePOST /mobile/sign-up/codeGET /internal/v1/identities?email=…, then …/{id}/code
Types the codePOST /mobile/sign-up/verifyGET /internal/v1/identities?email=…, then …/{id}/code-checks
Forgot their passwordPOST /mobile/forgot-passwordGET /internal/v1/identities?email=…, then …/{id}/password-email
Uses the appGET /api/me, with the access tokenNothing: your backend checks the token with OI's public keys

Trying it with Otoko Identity on your own machine?

The examples use https://identity.example.com for Otoko Identity. With OI running locally in Docker, its address is http://localhost:8001 and the console is at http://localhost:3100/admin. Your app runs on localhost as usual.

With a coding agent

To have Claude Code, Cursor or another coding agent do these steps in your project, paste it this prompt. Check what it writes against the steps below.

Agent prompt

Paste this into your coding agent, in your mobile app's and backend's project. It tells you what to register on the console, then writes sign-in, sign-up, forgot password, refresh and sign-out through your backend, the routes Otoko Identity calls, and the token check.

Show the full prompt

Connect this mobile app's sign-in to Otoko Identity, through its backend

You are connecting the sign-in of the mobile app you're working in to Otoko Identity (OI). A mobile app has no browser pages and needs no OI library: it signs people in on its own screens and talks only to its own backend, and the backend calls OI's API with the app's API key, which never leaves the server. The backend gives the app an access token and a refresh token, checks the access token on every API call, and is also the backend OI calls: on every sign-in, when a session ends, and when an account is made. Work through the steps below in order, and stop where a step says to wait for the person.

Scope

  • The backend: sign-in, refresh and sign-out; sign-up with a code OI emails; forgot password; a protected GET /api/me that makes the person's user on their first request; and the three routes OI calls, /internal/v1/sign-in-check, /internal/v1/session-ends and the signed /internal/v1/account-created.
  • The app: sign-in, sign-up, code and forgot-password screens, and a home screen that calls the API and signs out, with the tokens in the phone's secure storage.
  • Change nothing unrelated to signing in.

Rules

  • The API key, the webhook secret and the signing secret live only in the backend's env file, which git ignores.
    • Never open, print or paste the whole env file, and never ask for a secret in the chat. To check a setting is there, look for its name only (for example grep -c '^IDENTITY_API_KEY=' .env).
    • Never put a secret in the mobile app (anyone can unpack an app and read it), a log line or a commit. The app holds only the backend's address.
  • Never send a person's password anywhere but the backend's own routes, and never log it.
  • The app keeps the tokens in the platform's secure storage (the Keychain on iOS, the Keystore on Android: expo-secure-store, flutter_secure_storage), never in AsyncStorage or plain preferences.
  • For the backend's token checks, use a maintained JWT library, such as jose for Node or PyJWT for Python. Never write them by hand.
  • Use https everywhere outside a local machine.

1. Look at the project

  • Find the app's stack (React Native with Expo and Flutter are the worked examples; Swift, Kotlin or Ionic take the same steps), its backend's (Express, Next.js route handlers and FastAPI are the worked examples), the backend's port (the examples use 3001), how the app calls it, and any sign-in either already has. If the backend isn't in this project, ask where it is.
  • Confirm with the person that it's a mobile app that signs in through its backend. If it's a web app, stop and send the person to https://identity-docs.otoko.com/quickstarts.

2. Tell the person what to register, then wait

The app is registered on OI's console; you can't do this part.

  1. Name the backend's env file: .env, or .env.local for Next.js. Check that git ignores it before anything is pasted, and add it to .gitignore if not.
  2. Tell the person to open https://identity.otoko.com/admin/apps/new and:
    • Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes: a mobile app signs in through its backend.
    • How people sign in: choose Mobile app. It has no app address and no return addresses. Keep the Client ID it suggests.
    • Backend and email: type the Backend address, where OI reaches the backend. With OI running in Docker on the same machine, that's http://host.docker.internal:3001, not localhost. Leave Send this app's emails through Otoko Identity's mail server ticked, unless the app has its own mail server: then they untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat.
    • Choose Create, then on Connect your app the Backend section's Copy all, and paste it into the backend's env file. The API key and the webhook secret are shown only now. The Mobile app section holds only the client ID, already in IDENTITY_ALLOWED_CLIENT_IDS: the mobile app gets none of the values.
    • Check the Login settings: on the app's Overview tab, keep Verify email for new accounts and Forgot password on. A mobile client has no Allow sign-up: the backend makes the accounts with the API key.
    • Make the signing secret: on the Security tab, under Webhook signing secret, choose Make signing secret, and paste the whsec_… value into the env file as IDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
  3. Ask them to tell you when it's done, and wait. Then check the paste by names only.

From then on, OI asks the backend on every sign-in: until it runs and answers /internal/v1/sign-in-check, nobody can sign in.

3. Settings

  • The backend: IDENTITY_URL, IDENTITY_API_KEY, IDENTITY_ALLOWED_CLIENT_IDS (the mobile client's ID), IDENTITY_CALLBACK_TOKEN (the webhook secret) and IDENTITY_WEBHOOK_SIGNING_SECRET (empty until the app has one), plus PORT=3001. Add an .env.example with the same names and placeholder values.
  • The app: only the backend's address. React Native: EXPO_PUBLIC_BACKEND_URL in .env. Flutter: --dart-define=BACKEND_URL=…, read in lib/api/backend.dart, with http://localhost:3001 when none is given. On the Android emulator, the computer is 10.0.2.2.

4. Install

  • Backend: Express express jose (dev: typescript tsx @types/express @types/node); Next.js jose; FastAPI fastapi, uvicorn[standard], pyjwt[crypto]>=2.14, httpx and python-dotenv.
  • App: React Native npx expo install expo-secure-store; Flutter flutter pub add http flutter_secure_storage.

5. The backend: the routes the app calls

One helper calls IDENTITY_URL followed by /internal/v1 with Authorization: Bearer <IDENTITY_API_KEY> and a JSON body, reading the answer as JSON only when it is JSON. A call that sends an email or makes an account also sends an Idempotency-Key, a new random UUID (reuse it if you add retries). Each route passes the person's IP address as client_ip where shown, so OI's limits fall on that person, not on the server. When OI refuses, the route answers with OI's status and {"error": <OI's key>, "retry_after_seconds": ...}, so the app can say what went wrong.

  • POST /mobile/sign-in {email, password}: calls POST /internal/v1/sessions/password with {"email", "password", "client_ip"}. OI checks the password and asks the sign-in check. A 200 answers the app {access_token, refresh_token, expires_in}.
  • POST /mobile/refresh {refresh_token}: calls POST /internal/v1/sessions/refreshes, and answers the new pair. The refresh token rotates: the old one stops working. 400 invalid_grant means the session is over.
  • POST /mobile/sign-out {refresh_token}: calls POST /internal/v1/sessions/sign-outs, which answers 204. OI then calls session-ends.
  • POST /mobile/sign-up {email, password, first_name, last_name, language}: calls POST /internal/v1/identities with those and "email_verified": false. On 201, calls POST /internal/v1/identities/{id}/code with {language}, and answers 202 even if that email failed (log it). 409 conflict means the email already has an account.
  • Finding an account by email, for the next three: GET /internal/v1/identities?email=…. A 404 or 422 means none; any other non-200 is a refusal to pass on.
  • POST /mobile/sign-up/code {email, language}: if there's an account, calls …/identities/{id}/code without waiting for it, logging a failure. Answers 202 either way.
  • POST /mobile/sign-up/verify {email, code}: with an account, calls …/identities/{id}/code-checks with {code, client_ip}, and answers 204, or OI's 400 invalid_code or 429. With none, calls POST /internal/v1/unknown-addresses/code-failures with {email, client_ip}, passes on a 429, and otherwise answers 400 invalid_code, the same as a wrong code.
  • POST /mobile/forgot-password {email}: if there's an account, calls …/identities/{id}/password-email with {"purpose": "reset"} without waiting for it. Answers 202 either way. OI emails a link to its own set-password page.

The answers the app must handle:

  • 401 invalid_credentials: a wrong email or password, and also an email not verified yet. Say so without saying which, and offer to enter the code.
  • 403 wrong_application: the sign-in check said no. 403 account_setup_incomplete: the person has a step still to do; show the app's own screen for it.
  • 429 rate_limited: pass on the wait, from retry_after_seconds.
  • 503 unavailable: OI couldn't ask the backend; try again later.
  • From sign-up: 409 conflict, password_too_short, password_compromised, and 503 mail_server_not_set_up.

Passkeys (optional, only if the person asks): POST /internal/v1/sessions/passkey-challenges gives WebAuthn's options and a challenge_token, good once for five minutes. The device's answer goes to POST /internal/v1/sessions/passkey-assertions with that token, and signs in like a password.

6. The backend: the token check and /api/me

Every route that needs a signed-in person checks the bearer access token, and answers 401 with WWW-Authenticate: Bearer to a missing or failing one:

  • ES256 only, with keys from IDENTITY_URL followed by /.well-known/jwks.json, cached by the library, and iss equal to IDENTITY_URL.
  • aud and azp both among IDENTITY_ALLOWED_CLIENT_IDS.
  • The typ claim in the token's payload is Bearer. It's a claim, not the JWT header's typ: with jose, check it among the claims, not with the typ option.
  • sub, exp, iat, jti and sid all present. Refuse a token with "service": true, and one whose sid is among the ended sessions.
  • When OI's keys can't be fetched at all (not a token naming an unknown key), answer 503 {"error": "unavailable"}: the token may be fine.

GET /api/me: look the user up by sub. If there's none, call IDENTITY_URL followed by /oauth/userinfo with the same access token, which answers sub, email and locale for these tokens, and upsert the user keyed by sub, never by email. A 401 from userinfo answers 401; userinfo unreachable or failing answers 503. Answer {"sub", "email", "client": <azp>, "locale"}. The API needs no CORS: the app isn't a browser.

7. The backend: the routes OI calls

Under /internal/v1. Each first checks Authorization: Bearer <IDENTITY_CALLBACK_TOKEN> in constant time, and answers 401 to anything else, or to every call when the setting is unset.

POST /internal/v1/sign-in-check
Authorization: Bearer <IDENTITY_CALLBACK_TOKEN>
Content-Type: application/json

{ "sub": "5b1c6f0e-0000-4000-8000-000000000000", "client_id": "your-client-id", "pending_actions": [] }

HTTP/1.1 200 OK
Content-Type: application/json

{ "allowed": true }
  • sign-in-check: log [sign-in-check] <sub> on <client_id>: allowed and answer {"allowed": true}. Leave a comment that a real app checks its own records here, such as a blocked account or an unpaid plan. Keep it read-only and fast (OI waits 3 seconds), and make no user here. Anything other than {"allowed": true} keeps the person out.
  • session-ends: the body is {"sids": [...], "sub": "..." or null, "ended_at": "..."}. Answer 400 unless sids is a list of strings. Store each sid among the ended sessions the token check reads, log [session-ends] <n> session(s), and answer 204. Without a 2xx, OI tries again for 6 hours.
  • account-created: read the raw body bytes, before any JSON parsing. Verify the Standard Webhooks signature: base64 of HMAC-SHA256 over webhook-id, a dot, webhook-timestamp, a dot, then the body. The key is IDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes after whsec_; when that's empty, it's IDENTITY_CALLBACK_TOKEN's own UTF-8 bytes. webhook-signature may hold several v1, entries separated by spaces: refuse more than 10, and accept any that matches, compared in constant time. Answer 401 to a missing header, a bad signature, or a webhook-timestamp that isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to a webhook-id already stored. Otherwise parse the body, and for "type": "account.created" upsert the user from data (sub, email, first_name, last_name, language; names may be null), keyed by sub as above, store the webhook-id, and answer 204. It's never sent for accounts the backend made itself through /internal/v1/identities, so /api/me still makes those users.

OI calls these server to server, with no cookies: keep them out of the backend's sign-in middleware and CSRF protection, or every sign-in fails. The examples keep the ended sessions, the webhook ids and the users in memory; say in your report that production needs a real store.

8. The app

  • It calls only the backend, with a timeout (15 seconds), and turns a refusal into a message from its error, such as wrong email or password, too many tries with the wait, or can't reach the server.
  • Screens: sign-in (email, password, and links to Create an account and Forgot password?); sign-up (email, password, first and last name, and the email language, en or de from the phone's); the code screen (the code, and Send a new code), after sign-up or from Haven't verified your email? Enter the code under a refused sign-in; forgot password; and a home screen with Ask the API who I am (GET /api/me) and Sign out. After the code, the person signs in.
  • Tokens: saved in secure storage after sign-in, and read on start to open the home screen when someone is signed in.
  • API calls send Authorization: Bearer <access token>. On a 401, refresh once (one refresh at a time, shared by calls that all got 401, as a refresh token works only once), save the new pair, and try again. Still 401, or a 400 from refresh: delete the tokens and show sign-in. A network error or a 503: keep the tokens, and try again later.
  • Sign out deletes the tokens at once, then calls /mobile/sign-out with the refresh token without waiting. A refresh that finishes after a sign-out keeps nothing, and signs out its new refresh token too.

9. Check it works

Start the backend (npm run dev, npm run dev -- -p 3001 for Next.js, or uvicorn app.main:app --port 3001 --env-file .env).

  1. curl -i http://localhost:3001/api/me and a POST to /internal/v1/sign-in-check with no bearer token must both answer 401.
  2. Sign-up sends a real email: ask the person for the address, never invent one. A POST to /mobile/sign-up with it answers 202. They give you the emailed 8-digit code for /mobile/sign-up/verify, which answers 204, then /mobile/sign-in answers the tokens. Never print the tokens or the password in full.

Then start the app pointed at the backend (npx expo start, or flutter run --dart-define=BACKEND_URL=http://10.0.2.2:3001), and ask the person to:

  1. Choose Create an account, type the code, then sign in. The backend's log shows [sign-in-check] … allowed.
  2. Choose Ask the API who I am. The app shows their sub, the mobile client's ID and their locale.
  3. Leave the app until the access token expires (30 minutes on a new app; the client's Access token lifespan can be set to one minute to try it), then ask again. The app renews the token and the call works.
  4. Choose Sign out. The log shows [session-ends] 1 session(s).
  5. Choose Forgot password?, open the emailed link, set a new password on OI's page, and sign in with it.

If sign-in answers 503 unavailable, OI can't reach the sign-in check: check the backend address. If every call to OI answers 401 invalid_api_key, IDENTITY_API_KEY isn't the app's current key. Can't reach the server on a phone means localhost isn't the computer there. For other errors, read https://identity-docs.otoko.com/troubleshooting.

Finish with a short report: the files you changed, the routes and screens you added, the settings the code reads (by name), and anything the person still has to do.

More detail

Register the app

  1. In the console, open Connect an app.

  2. Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes: a mobile app signs in through your backend.

  3. How people sign in: choose Mobile app. It has no app address and no return addresses. Keep the Client ID it suggests, or type your own.

  4. Backend and email: type the Backend address, where OI reaches your backend, such as http://localhost:3001. With OI running in Docker on your own machine, that's http://host.docker.internal:3001, not localhost. Then, for the emails:

    Otoko Identity emails sign-up codes, forgot-password codes and invitations. Leave Send this app's emails through Otoko Identity's mail server ticked, and the app needs no mail server of its own; a Reply-to address is optional. Only if your app has its own mail server, untick it, type the From address OI sends from, and fill in the Mail server section that appears: host, port, encryption, username and password, the last two together, and its timeouts. It's saved when the app is made, and the last step offers Send test email.

  5. Choose Create. On Connect your app, choose the Backend section's Copy all. Its values all go to the backend: IDENTITY_URL, IDENTITY_APP_ID, the API key (IDENTITY_API_KEY), the webhook secret (IDENTITY_CALLBACK_TOKEN) and IDENTITY_ALLOWED_CLIENT_IDS, which is the mobile client's ID. The API key and webhook secret are shown only now. The Mobile app section holds only that client ID, IDENTITY_CLIENT_ID, which the tokens name: the backend already checks it through IDENTITY_ALLOWED_CLIENT_IDS, and the phone app needs nothing from the kit.

  6. Check the app's Login settings. On the app's Overview tab, under Login, Verify email for new accounts and Forgot password are on for a new app: keep them on. A mobile client has no Allow sign-up: that switch adds a link to OI's own sign-in page, which a mobile app never shows. Your backend makes the accounts with the API key instead.

  7. On the app's Security tab, under Webhook signing secret, choose Make signing secret. It's shown once, as whsec_…: it goes to the backend as IDENTITY_WEBHOOK_SIGNING_SECRET, and checks the signature on account.created. Without one, OI signs with the webhook secret, which every call also carries.

Warning

From now on, OI asks your backend on every sign-in. Until the backend is running and answers /internal/v1/sign-in-check, nobody can sign in.

Settings

The backend

The IDENTITY_ values come from the Backend section's Copy all. The file holds the API key and the webhook secret, so keep it out of git.

Copy .env.example to .env.

.env.example
# Copy to .env. The IDENTITY_ values come from Connect an app's Backend section (its Copy all).
# This file holds secrets: keep it out of git, and never put the API key in the mobile app.
IDENTITY_URL=https://identity.example.com
IDENTITY_API_KEY=the-api-key-shown-once
IDENTITY_ALLOWED_CLIENT_IDS=your-mobile-client-id
IDENTITY_CALLBACK_TOKEN=the-webhook-secret-shown-once
# The webhook signing secret, whsec_..., made on the app's Security tab. Leave it empty until the app has one: until
# then, account.created is signed with IDENTITY_CALLBACK_TOKEN.
IDENTITY_WEBHOOK_SIGNING_SECRET=
PORT=3001

The mobile app

The app needs only your backend's address. Anything built into an app can be read by whoever has it, so it never holds the API key or any secret.

Copy .env.example to .env. Expo builds names that start with EXPO_PUBLIC_ into the app.

.env.example
# Copy to .env. Your backend's address, built into the app: never put the API key or any secret here.
# On the Android emulator, your computer is 10.0.2.2: EXPO_PUBLIC_BACKEND_URL=http://10.0.2.2:3001
EXPO_PUBLIC_BACKEND_URL=http://localhost:3001

Install

The backend

A new backend. For one you already have, skip the first two lines: the third sets type=module, which the examples' imports need, so check nothing of yours still uses require.

mkdir my-backend && cd my-backend
npm init -y
npm pkg set type=module scripts.dev="tsx watch --env-file=.env src/server.ts" scripts.typecheck="tsc --noEmit"
npm install express jose
npm install -D typescript tsx @types/express @types/node

The mobile app

A new app (skip the first two lines for an app you already have):

npx create-expo-app@latest my-app
cd my-app
npm run reset-project
npx expo install expo-secure-store

npm run reset-project clears the starter's screens: answer n to delete them, or y to keep them in example/.

Add the code

The backend: the routes the app calls

Each route passes what the person typed on to OI with the API key, and the person's IP address as client_ip, so OI's limits on wrong passwords and codes fall on that person and not on your server. When OI refuses, the route answers with OI's status and {"error": "<OI's key>"}, such as invalid_credentials, so the app can say what went wrong. Forgot password and a new code answer 202 whether or not the email has an account, so nobody can use them to find out who has one.

Where these files go

mobile.ts
oi.ts
server.ts
tsconfig.json
  • src/oi.ts: the calls to OI's internal API, with the API key.
  • src/routes/mobile.ts: the routes the app calls, under /mobile.
  • src/server.ts: the app, with /mobile, GET /api/me behind requireToken, which makes the person's user if there's none yet, and OI's routes under /internal/v1.
  • tsconfig.json: for npm run typecheck. tsx runs the code without a build step.
import { randomUUID } from 'node:crypto';

const internalApi = `${process.env.IDENTITY_URL}/internal/v1`;

/** OI's answer: its status, and its JSON body, if it sent one. On a refusal, body.error is OI's key for it. */
export type OIAnswer = { status: number; body: Record<string, unknown> | null };

/**
 * Calls OI's internal API with this app's API key, which only this server holds. A call that sends an email or
 * makes an account also sends a new Idempotency-Key. This code doesn't retry. If you add retries, keep the key for
 * the call and send it again: OI then answers the retry as the first, without a second email or account.
 */
export async function callOI(path: string, body?: object, options: { createsSomething?: boolean } = {}): Promise<OIAnswer> {
  const headers: Record<string, string> = { Authorization: `Bearer ${process.env.IDENTITY_API_KEY}` };
  if (body) {
    headers['Content-Type'] = 'application/json';
  }
  if (options.createsSomething) {
    headers['Idempotency-Key'] = randomUUID();
  }

  const res = await fetch(`${internalApi}${path}`, {
    method: body ? 'POST' : 'GET',
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  // Only a JSON answer is read, OI's errors (application/problem+json) included: a proxy in front of OI can answer an
  // outage with an HTML page, and a 204 has no body at all.
  const text = await res.text();
  const isJson = /\bjson\b/.test(res.headers.get('content-type') ?? '');
  return { status: res.status, body: isJson && text ? JSON.parse(text) : null };
}

/**
 * The id of the account with this email in this app, or null if there's none. Or OI's refusal, such as 429
 * rate_limited, to pass on: it comes whether the email has an account or not, so it tells nobody who has one.
 */
export async function findIdentityId(email: unknown): Promise<{ id: string | null } | { refused: OIAnswer }> {
  const answer = await callOI(`/identities?email=${encodeURIComponent(String(email))}`);
  if (answer.status === 404 || answer.status === 422) {
    return { id: null }; // nobody has this email, or it isn't an email address
  }
  if (answer.status !== 200) {
    return { refused: answer };
  }
  return { id: answer.body!.id as string };
}

The backend: checking tokens

Your API checks every access token before trusting it, with Otoko Identity's public keys. A token passes only when:

CheckWhat it means
SignatureES256, with a key from <issuer>/.well-known/jwks.json.
issIs Otoko Identity's address, IDENTITY_URL, exactly.
aud and azpAre both one of your app's client IDs, IDENTITY_ALLOWED_CLIENT_IDS.
sub, exp, iat, jti, sidAre all there, and exp is still in the future.
typIs Bearer: an access token, not an ID token.
serviceIsn't true. A service token has nobody signed in, so an API for people refuses it.
sidIsn't a session Otoko Identity said had ended.

The token names the person (sub) and the client they signed in with (azp), but not their email or roles. A front end reads those from OI's userinfo endpoint. An API that needs them looks the person up by sub in its own database, or asks userinfo with the same token.

src/token.ts: the token check, with jose.

src/token.ts
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';

import { endedSessions } from './identity.js';

const issuer = process.env.IDENTITY_URL!;
const allowedClientIds = process.env.IDENTITY_ALLOWED_CLIENT_IDS!.split(',').map((id) => id.trim());
// OI's public keys, fetched once and kept. jose fetches them again when OI signs with a new key.
const remoteKeys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));

/** OI's keys couldn't be fetched, as OI or the network is down. That says nothing about the token: answer 503. */
export class KeysUnavailable extends Error {}

const keys: JWTVerifyGetKey = async (header, token) => {
  try {
    return await remoteKeys(header, token);
  } catch (err) {
    if (err instanceof errors.JWKSNoMatchingKey || err instanceof errors.JWKSMultipleMatchingKeys) {
      throw err; // the token names no key of OI's: a bad token
    }
    throw new KeysUnavailable("OI's keys couldn't be fetched", { cause: err });
  }
};

/** Checks an access token OI gave one of this app's clients, and gives back its claims. Throws for any other. */
export async function verifyAccessToken(token: string): Promise<JWTPayload> {
  const { payload } = await jwtVerify(token, keys, {
    issuer,
    algorithms: ['ES256'],
    audience: allowedClientIds, // aud must be one of this app's clients
    requiredClaims: ['sub', 'exp', 'iat', 'jti', 'sid'],
  });

  if (!allowedClientIds.includes(payload.azp as string)) {
    throw new Error("azp isn't one of this app's clients");
  }
  if (payload.typ !== 'Bearer') {
    throw new Error('not an access token');
  }
  if (payload.service === true) {
    throw new Error('a service token, with nobody signed in');
  }
  if (endedSessions.has(payload.sid as string)) {
    throw new Error('the session has ended');
  }

  return payload;
}

The backend: the routes Otoko Identity calls

Otoko Identity calls three routes on your backend. Each call is a POST with the webhook secret (IDENTITY_CALLBACK_TOKEN) as a bearer token in the Authorization header, so check it before anything else, in constant time.

RouteOI sendsYour answerWhen
/internal/v1/sign-in-check{"sub": "…", "client_id": "…", "pending_actions": []}{"allowed": true} lets the person in; anything else keeps them outOn every sign-in, after the password. It's waited for 3 seconds, so keep it read-only. With no answer, the app's If the backend can't be reached decides: Refuse sign-in, the default, or Allow sign-in.
/internal/v1/session-ends{"sids": ["…"], "sub": "…" or null, "ended_at": "…"}Any 2xx, once you've kept the sidsWhen someone signs out, or an admin ends their sessions. Without a 2xx, OI tries again for 6 hours.
/internal/v1/account-created{"type": "account.created", "data": {"sub": "…", "email": "…", …}}, signedAny 2xx, once you've kept the user; 401 for a bad signatureOnce for each new person: a verified sign-up, an accepted invitation, or a first sign-in through an identity provider such as Google. client_id is null for an invitation. Without a 2xx, OI tries again for about 31 hours.

Each sid is the sid claim of that session's access tokens. Refuse those tokens from then on, for as long as one could still be valid: the access token lifetime.

account.created is also signed, as Standard Webhooks signs: check its webhook-signature against the raw body before anything else reads it, with the app's webhook signing secret (IDENTITY_WEBHOOK_SIGNING_SECRET), or the webhook secret until the app has one. See Verify its signature. It can come more than once, so keep each webhook-id and make the user only once, keyed by its sub. Make the user on the person's first request too, from OI's userinfo: the event can be late, or dead. See Create your user on its first request.

Where these files go

identity.ts
identity.ts
users.ts
  • src/identity.ts: the webhook secret and signature checks, and the ended sessions.
  • src/routes/identity.ts: the three routes, under /internal/v1.
  • src/users.ts: this app's users, made by account.created or on the person's first request to /api/me, from OI's userinfo.
import { createHmac, timingSafeEqual } from 'node:crypto';
import type { IncomingHttpHeaders } from 'node:http';

/** Whether a call really comes from OI: it sends the webhook secret as a bearer token. */
export function isFromOI(authorization: string | undefined): boolean {
  const secret = process.env.IDENTITY_CALLBACK_TOKEN;
  if (!secret) {
    return false; // no secret set: refuse every call, rather than match "Bearer undefined"
  }
  const sent = Buffer.from(authorization ?? '');
  const expected = Buffer.from(`Bearer ${secret}`);
  return sent.length === expected.length && timingSafeEqual(sent, expected);
}

const SIGNATURE_VERSION = 'v1';
const SIGNING_SECRET_PREFIX = 'whsec_';
const TOLERANCE_SECONDS = 5 * 60;
// One signature per secret in use, so a rotation sends two.
const MAX_SIGNATURES = 10;
const UNIX_SECONDS_PATTERN = /^[0-9]+$/;

// A whsec_ signing secret's key is the base64 after the prefix; the webhook secret's, its own UTF-8 bytes.
function readKey(secret: string): Buffer {
  return secret.startsWith(SIGNING_SECRET_PREFIX)
    ? Buffer.from(secret.slice(SIGNING_SECRET_PREFIX.length), 'base64')
    : Buffer.from(secret, 'utf8');
}

function readHeader(headers: IncomingHttpHeaders, name: string): string | undefined {
  const value = headers[name];
  return typeof value === 'string' ? value : undefined;
}

/**
 * Whether account.created was signed by OI within 5 minutes of this clock, as Standard Webhooks signs: with the app's
 * whsec_ signing secret (IDENTITY_WEBHOOK_SIGNING_SECRET) or, until the app has one, its webhook secret. `body` is the
 * raw bytes received, before any parsing.
 */
export function isSignedByOI(headers: IncomingHttpHeaders, body: Buffer): boolean {
  const secret = process.env.IDENTITY_WEBHOOK_SIGNING_SECRET || process.env.IDENTITY_CALLBACK_TOKEN;
  const id = readHeader(headers, 'webhook-id');
  const timestamp = readHeader(headers, 'webhook-timestamp');
  const signatureHeader = readHeader(headers, 'webhook-signature');
  if (!secret || id === undefined || timestamp === undefined || signatureHeader === undefined) {
    return false;
  }
  if (!UNIX_SECONDS_PATTERN.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
    return false;
  }
  const entries = signatureHeader.split(' ');
  if (entries.length > MAX_SIGNATURES) {
    return false;
  }

  const expected = createHmac('sha256', readKey(secret)).update(`${id}.${timestamp}.`).update(body).digest();
  return entries.some((entry) => {
    const [version, signature = ''] = entry.split(',');
    const given = Buffer.from(signature, 'base64');
    return version === SIGNATURE_VERSION && given.length === expected.length && timingSafeEqual(given, expected);
  });
}

// OI's sessions that ended (a sign-out, or an admin ending them). Each must stay refused for as long as its access
// tokens could still work, the access token lifetime. A Set in memory suits development only: in production, keep
// them in Redis or your database, each with that lifetime as its expiry.
export const endedSessions = new Set<string>();

// The account.created deliveries already stored, by their webhook-id: OI may send one again, and a replay does.
// In production, a unique column in your database.
export const storedDeliveries = new Set<string>();

The mobile app

The app calls only your backend, from the Server tabs above. After sign-up, the person types the emailed code, then signs in. When an API call answers 401, the access token has expired: the app swaps the refresh token for a new pair once, and tries again. If that fails too, the session is over, and the person signs in again. A 503 unavailable from your API is different: your backend couldn't fetch OI's keys to check the token, so the app keeps its tokens and the person tries again later.

Where these files go

tokens.ts
backend.ts
styles.ts
sign-in.tsx
sign-up.tsx
verify.tsx
forgot-password.tsx
_layout.tsx
index.tsx
  • src/auth/tokens.ts: the tokens, in the phone's secure storage with expo-secure-store.
  • src/api/backend.ts: the calls to your backend, the token renewal, and what to tell the person when something is refused.
  • src/ui/styles.ts: the few styles the screens share.
  • src/app/_layout.tsx and src/app/index.tsx: the screens' stack, and the home screen. These replace the blank ones reset-project made.
  • src/app/(auth)/sign-in.tsx, sign-up.tsx, verify.tsx and forgot-password.tsx: the screens before signing in. (auth) groups them without adding to their address, so the sign-in screen is /sign-in.
import * as SecureStore from 'expo-secure-store';

// The tokens live in the phone's secure storage, the Keychain on iOS and the Keystore on Android, and never in
// AsyncStorage, which any code in the app can read and which backups copy. One item each, as an item may hold
// only about 2 KB.
const ACCESS_TOKEN = 'identity.access_token';
const REFRESH_TOKEN = 'identity.refresh_token';

export type Tokens = { access_token: string; refresh_token: string };

export async function saveTokens(tokens: Tokens): Promise<void> {
  await SecureStore.setItemAsync(ACCESS_TOKEN, tokens.access_token);
  await SecureStore.setItemAsync(REFRESH_TOKEN, tokens.refresh_token);
}

/** The tokens, or null when nobody is signed in on this phone. */
export async function readTokens(): Promise<Tokens | null> {
  const access_token = await SecureStore.getItemAsync(ACCESS_TOKEN);
  const refresh_token = await SecureStore.getItemAsync(REFRESH_TOKEN);
  return access_token && refresh_token ? { access_token, refresh_token } : null;
}

export async function clearTokens(): Promise<void> {
  await SecureStore.deleteItemAsync(ACCESS_TOKEN);
  await SecureStore.deleteItemAsync(REFRESH_TOKEN);
}

Using something else?

PartFrameworkWhere
BackendNestJSA MobileController at mobile that calls OI with fetch, a TokenGuard using jose, and an IdentityController at internal/v1
BackendDjangoViews in yourapp/mobile_views.py that call OI with httpx, marked @csrf_exempt as the app isn't a browser, and PyJWT's PyJWKClient for the token check
MobileSwift (iOS)URLSession for the calls, and the tokens in the Keychain
MobileKotlin (Android)Ktor or Retrofit for the calls, and the tokens encrypted with a key in the Android Keystore
MobileIonic or Capacitorfetch for the calls, and the tokens in a secure-storage plugin, never in localStorage

Run and check

Start the backend first.

npm run dev
  1. Check the backend's doors are locked. Both must answer 401:

    curl -i http://localhost:3001/api/me
    curl -i -X POST http://localhost:3001/internal/v1/sign-in-check -H "Content-Type: application/json" -d '{"sub":"x","client_id":"x","pending_actions":[]}'
  2. Try sign-up without the app. This answers 202, and OI emails an 8-digit code to the address:

    curl -i -X POST http://localhost:3001/mobile/sign-up -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"a-long-password","first_name":"Ada","last_name":"Lovelace","language":"en"}'

    Then send the code, which answers 204, and sign in, which answers the tokens:

    curl -i -X POST http://localhost:3001/mobile/sign-up/verify -H "Content-Type: application/json" -d '{"email":"[email protected]","code":"12345678"}'
    curl -i -X POST http://localhost:3001/mobile/sign-in -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"a-long-password"}'

Then start the app, pointed at the backend. On the Android emulator, your computer is 10.0.2.2; on a real phone, use your computer's address on the Wi-Fi, such as http://192.168.1.20:3001.

npx expo start

Press a for the Android emulator or i for the iOS simulator, or scan the QR code with Expo Go.

  1. Choose Create an account, then type the code OI emails you, then sign in. The backend's log shows [sign-in-check] … allowed.
  2. Choose Ask the API who I am. The app shows your sub, the mobile client's ID and your locale.
  3. Leave the app until the access token expires, then ask again. The app renews the token and the call works. (A token lasts as long as the client's Access token lifespan, 30 minutes on a new app. Set it to one minute to try this quickly.)
  4. Choose Sign out. The backend's log shows [session-ends] 1 session(s).
  5. On the sign-in screen, choose Forgot password? and type your email. Open the emailed link on the phone, set a new password on OI's page, then sign in with it in the app.

Before going live

  • Serve the backend over https, and give OI its live address as the app's backend address, on the app's Overview tab. Point the app's release builds at it (EXPO_PUBLIC_BACKEND_URL, or --dart-define=BACKEND_URL=).
  • Keep the API key and the webhook secret on the backend only, in your host's secret settings, never in the app: anyone can unpack an app and read what's in it. A leaked API key is replaced on the app's Security tab, under API keys.
  • Let a Flutter release build use the network: add <uses-permission android:name="android.permission.INTERNET"/> to android/app/src/main/AndroidManifest.xml. The starter has it only for debug builds.
  • Pass the person's real address on as client_ip. Behind a proxy or a load balancer, set your backend to read the address it adds (Express's trust proxy, uvicorn's --proxy-headers), or OI counts everyone's wrong passwords as one person's. Next.js isn't told who connected: set CLIENT_IP_HEADER to the header your host fills in, such as x-real-ip on Vercel, never the left of x-forwarded-for, which the caller writes.
  • Limit your own /mobile routes too, by address: sign-up, a new code and forgot password each send an email.
  • Keep ended sessions in a real store, each with the access token lifetime as its expiry, so every copy of the backend refuses them.
  • Sign-up says when an email already has an account (409 conflict), which tells anyone who tries whether an address is a customer's. If that matters for your app, answer 202 all the same, and send that person a forgot-password email instead.

If something goes wrong

What you seeWhyWhat to do
Sign-in answers 503 unavailableOI can't reach your backend's sign-in checkStart the backend first. With OI in Docker, the backend address uses host.docker.internal, not localhost.
Sign-in answers 401 invalid_credentials with the right passwordThe email isn't verified yet: OI answers as it does for a wrong password, so nobody learns the account existsChoose Haven't verified your email? Enter the code under the message, and type the code from the email, or choose Send a new code.
Sign-in answers 403 account_setup_incompleteYour backend put a required action on the account, such as accepting new terms, and it's still to doShow your own screen for it. Once it's done, your backend calls DELETE /internal/v1/identities/{id}/required-actions/{action} with the API key, and the person signs in again.
Sign-in answers 403 wrong_applicationYour sign-in check answered something other than {"allowed": true}Check what /internal/v1/sign-in-check answers for this person.
Every call to OI answers 401 invalid_api_keyIDENTITY_API_KEY isn't the app's current API keyCopy it again, or rotate it on the app's Security tab and use the new one.
Sign-up answers 503 mail_server_not_set_upThe app sends email through a mail server that isn't set upOn the app's Email tab, send through OI's mail server, or finish setting up your own.
/api/me answers 503 unavailableYour backend can't fetch OI's keys to check tokens (not the sign-in check above)Check that the backend reaches IDENTITY_URL. The app keeps its tokens, so the person doesn't sign in again.
/api/me answers 401 right after signing inIDENTITY_ALLOWED_CLIENT_IDS isn't the mobile client's ID, or IDENTITY_URL isn't the issuer exactlyUse the values from the Backend section's Copy all, with no trailing slash.
The app says Can't reach the serverThe phone can't reach the address: localhost on a phone, or on the Android emulator, isn't your computerUse 10.0.2.2 on the Android emulator, or your computer's Wi-Fi address on a real phone. A React Native release build on Android also refuses plain http, so give it an https address. A Flutter release build on Android needs the internet permission, as in step 6.
The set-password link says it's no longer validLinks last 10 minutes on a new appChoose Forgot password? again.

Tested with Express 5.3.0, jose 6.2.18 · Next.js 16.4.6 · FastAPI 0.165.0, httpx 0.28.1, PyJWT 2.15.1, Python 3.14 · Expo SDK 58, React Native 0.88.1, TypeScript 6.0. The backends were run against OI; the React Native screens were type-checked and bundled, not run on a phone. The Flutter screens are written for Flutter 3 with http 1 and flutter_secure_storage 10.