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-endsand 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 person | The app calls your backend | Your backend calls OI |
|---|---|---|
| Signs in | POST / | POST /, then OI asks your sign-in-check |
| Is using the app, and the access token expires | POST / | POST / |
| Signs out | POST / | POST /, then OI calls your session-ends |
| Signs up | POST / | POST /, then POST / |
| Asks for a new code | POST / | GET /, then …/ |
| Types the code | POST / | GET /, then …/ |
| Forgot their password | POST / | GET /, then …/ |
| Uses the app | GET /, with the access token | Nothing: 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.
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/methat makes the person's user on their first request; and the three routes OI calls,/internal/v1/sign-in-check,/internal/v1/session-endsand 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 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
- 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.
- Name the backend's env file:
.env, or.env.localfor Next.js. Check that git ignores it before anything is pasted, and add it to.gitignoreif not. - 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, notlocalhost. 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 asIDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
- 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) andIDENTITY_WEBHOOK_SIGNING_SECRET(empty until the app has one), plusPORT=3001. Add an.env.examplewith the same names and placeholder values. - The app: only the backend's address. React Native:
EXPO_PUBLIC_BACKEND_URLin.env. Flutter:--dart-define=BACKEND_URL=…, read inlib/api/backend.dart, withhttp://localhost:3001when none is given. On the Android emulator, the computer is10.0.2.2.
4. Install
- Backend: Express
express jose(dev:typescript tsx @types/express @types/node); Next.jsjose; FastAPIfastapi,uvicorn[standard],pyjwt[crypto]>=2.14,httpxandpython-dotenv. - App: React Native
npx expo install expo-secure-store; Flutterflutter 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}: callsPOST /internal/v1/sessions/passwordwith{"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}: callsPOST /internal/v1/sessions/refreshes, and answers the new pair. The refresh token rotates: the old one stops working. 400invalid_grantmeans the session is over.POST /mobile/sign-out{refresh_token}: callsPOST /internal/v1/sessions/sign-outs, which answers 204. OI then callssession-ends.POST /mobile/sign-up{email, password, first_name, last_name, language}: callsPOST /internal/v1/identitieswith those and"email_verified": false. On 201, callsPOST /internal/v1/identities/{id}/codewith{language}, and answers 202 even if that email failed (log it). 409conflictmeans 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}/codewithout waiting for it, logging a failure. Answers 202 either way.POST /mobile/sign-up/verify{email, code}: with an account, calls…/identities/{id}/code-checkswith{code, client_ip}, and answers 204, or OI's 400invalid_codeor 429. With none, callsPOST /internal/v1/unknown-addresses/code-failureswith{email, client_ip}, passes on a 429, and otherwise answers 400invalid_code, the same as a wrong code.POST /mobile/forgot-password{email}: if there's an account, calls…/identities/{id}/password-emailwith{"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. 403account_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, fromretry_after_seconds. - 503
unavailable: OI couldn't ask the backend; try again later. - From sign-up: 409
conflict,password_too_short,password_compromised, and 503mail_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_URLfollowed by/.well-known/jwks.json, cached by the library, andissequal toIDENTITY_URL. audandazpboth amongIDENTITY_ALLOWED_CLIENT_IDS.- The
typclaim in the token's payload isBearer. It's a claim, not the JWT header'styp: with jose, check it among the claims, not with thetypoption. sub,exp,iat,jtiandsidall present. Refuse a token with"service": true, and one whosesidis 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>: allowedand 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 unlesssidsis a list of strings. Store eachsidamong 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 overwebhook-id, a dot,webhook-timestamp, a dot, then the body. The key isIDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes afterwhsec_; when that's empty, it'sIDENTITY_CALLBACK_TOKEN's own UTF-8 bytes.webhook-signaturemay hold severalv1,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 awebhook-timestampthat isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to awebhook-idalready stored. Otherwise parse the body, and for"type": "account.created"upsert the user fromdata(sub,email,first_name,last_name,language; names may be null), keyed bysubas above, store thewebhook-id, and answer 204. It's never sent for accounts the backend made itself through/internal/v1/identities, so/api/mestill 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,
enordefrom 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-outwith 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).
curl -i http://localhost:3001/api/meand a POST to/internal/v1/sign-in-checkwith no bearer token must both answer 401.- Sign-up sends a real email: ask the person for the address, never invent one. A POST to
/mobile/sign-upwith it answers 202. They give you the emailed 8-digit code for/mobile/sign-up/verify, which answers 204, then/mobile/sign-inanswers 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:
- Choose Create an account, type the code, then sign in. The backend's log shows
[sign-in-check] … allowed. - Choose Ask the API who I am. The app shows their
sub, the mobile client's ID and their locale. - 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.
- Choose Sign out. The log shows
[session-ends] 1 session(s). - 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
- https://identity-docs.otoko.com/quickstarts/mobile-app: this setup, step by step, with code for each framework.
- https://identity-docs.otoko.com/app-settings/mobile-apps: the mobile client, and https://identity-docs.otoko.com/api-reference/your-backends-calls#sessions for its calls.
- https://identity-docs.otoko.com/api-reference/calls-to-your-backend: the routes OI calls, and verifying the signature.
- https://identity-docs.otoko.com/api-reference/tokens: checking tokens and lifetimes.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
Register the app
-
In the console, open Connect an app.
-
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.
-
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.
-
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'shttp://host.docker.internal:3001, notlocalhost. 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.
-
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) andIDENTITY_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 throughIDENTITY_ALLOWED_CLIENT_IDS, and the phone app needs nothing from the kit. -
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.
-
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 asIDENTITY_WEBHOOK_SIGNING_SECRET, and checks the signature onaccount.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.
# 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=3001Copy .env.example to .env.local, which Next.js reads on the server only.
# Copy to .env.local. 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=
# Your own: the header your host or proxy puts the person's address in, such as x-real-ip on Vercel. Leave it
# out with nothing in front of the app.
# CLIENT_IP_HEADER=x-real-ipCopy .env.example to .env.
# 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=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.
# 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:3001The address is given when you run or build the app, with --dart-define=BACKEND_URL=…, as in step 5. lib/api/backend.dart reads it, and uses http://localhost:3001 when none is given.
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/nodeA new backend (skip the first two lines for one you already have):
npx create-next-app@latest my-backend --ts --app --eslint --yes --no-src-dir --import-alias "@/*"
cd my-backend
npm install joseA new backend, with Python 3.10 or later. First save this as requirements.txt:
fastapi
uvicorn[standard]
pyjwt[crypto]>=2.14
httpx
python-dotenvThen:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install -r requirements.txtThe 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-storenpm run reset-project clears the starter's screens: answer n to delete them, or y to keep them in example/.
A new app (skip the first two lines for an app you already have):
flutter create my_app
cd my_app
flutter pub add http flutter_secure_storageThen delete test/widget_test.dart: it tests the starter's counter, which step 4 replaces.
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
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/mebehindrequireToken, which makes the person's user if there's none yet, and OI's routes under/internal/v1.tsconfig.json: fornpm run typecheck.tsxruns 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 };
}Where these files go
lib/oi.ts: the calls to OI's internal API, with the API key, and what the routes share.app/mobile/…/route.ts: one route handler for each route the app calls.app/api/me/route.ts: the protected API route. It makes the person's user if there's none yet.
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,
cache: 'no-store',
});
// 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 };
}
/** What the app sent, or nothing if it wasn't JSON. */
export async function readBody(request: Request): Promise<Record<string, unknown>> {
try {
return await request.json();
} catch {
return {};
}
}
/**
* The person's address, so OI's limits on wrong passwords and codes fall on them, not on this server. A route
* handler isn't told who connected, so the address comes from a header your host or proxy sets, named in
* CLIENT_IP_HEADER: x-real-ip on Vercel, or on nginx with proxy_set_header X-Real-IP $remote_addr. Never the left
* of x-forwarded-for, which the caller can write. With no header named, the address is left out, and OI's limits
* per account still hold.
*/
export function clientIp(request: Request): string | null {
const header = process.env.CLIENT_IP_HEADER;
return header ? request.headers.get(header)?.trim() || null : null;
}
/** Passes OI's refusal on, with its status and its key, such as invalid_credentials. */
export function refusal(answer: OIAnswer): Response {
return Response.json(
{ error: answer.body?.error, retry_after_seconds: answer.body?.retry_after_seconds },
{ status: answer.status },
);
}
/** The two tokens, and how many seconds the access token lasts. */
export function tokens(answer: OIAnswer): Response {
const { access_token, refresh_token, expires_in } = answer.body!;
return Response.json({ access_token, refresh_token, expires_in });
}Where these files go
app/oi.py: the calls to OI's internal API, with the API key.app/mobile_routes.py: the routes the app calls, under/mobile.app/main.py: the app, with the two routers,GET /api/me, which makes the person's user if there's none yet, and a handler that passes on OI's refusals, such as 429 and 403flow_not_offered.
"""Calls OI's internal API with this app's API key, which only this server holds."""
import os
import uuid
import httpx
_client = httpx.AsyncClient(
base_url=f"{os.environ['IDENTITY_URL']}/internal/v1",
headers={"Authorization": f"Bearer {os.environ['IDENTITY_API_KEY']}"},
timeout=10,
)
async def call_oi(path: str, body: dict | None = None, *, creates_something: bool = False) -> httpx.Response:
"""OI's answer. 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."""
headers = {"Idempotency-Key": str(uuid.uuid4())} if creates_something else {}
if body is None:
return await _client.get(path, headers=headers)
return await _client.post(path, json=body, headers=headers)
class OIRefused(Exception):
"""OI refused a call, such as 429 rate_limited. main.py passes its answer on to the app."""
def __init__(self, answer: httpx.Response):
self.answer = answer
async def find_identity_id(email: str) -> str | None:
"""The id of the account with this email in this app, or None if there's none."""
answer = await _client.get("/identities", params={"email": email})
if answer.status_code in (404, 422):
return None # nobody has this email, or it isn't an email address
if answer.status_code != 200:
raise OIRefused(answer)
return answer.json()["id"]The backend: checking tokens
Your API checks every access token before trusting it, with Otoko Identity's public keys. A token passes only when:
| Check | What it means |
|---|---|
| Signature | ES256, with a key from <issuer>/. |
iss | Is Otoko Identity's address, IDENTITY_URL, exactly. |
aud and azp | Are both one of your app's client IDs, IDENTITY_ALLOWED_CLIENT_IDS. |
sub, exp, iat, jti, sid | Are all there, and exp is still in the future. |
typ | Is Bearer: an access token, not an ID token. |
service | Isn't true. A service token has nobody signed in, so an API for people refuses it. |
sid | Isn'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.
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;
}lib/token.ts: the token check, with jose.
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
import { endedSessions } from './identity';
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;
}app/token.py: the token check, with PyJWT.
"""Checks the access tokens OI gives this app's clients."""
import os
import jwt
from .identity_routes import ended_sessions
ISSUER = os.environ["IDENTITY_URL"]
ALLOWED_CLIENT_IDS = [client_id.strip() for client_id in os.environ["IDENTITY_ALLOWED_CLIENT_IDS"].split(",")]
# OI's public keys, fetched when first needed and kept. PyJWT fetches them again for a key it hasn't seen, at most
# every 30 seconds, so tokens naming made-up keys can't make this server call OI on every request.
_keys = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json", cooldown_duration=30, timeout=5)
def verify_access_token(token: str) -> dict:
"""The claims of an access token OI gave one of this app's clients. Raises jwt.PyJWTError for any other, and
jwt.PyJWKClientConnectionError when OI's keys can't be fetched."""
signing_key = _keys.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key.key,
algorithms=["ES256"],
issuer=ISSUER,
audience=ALLOWED_CLIENT_IDS, # aud must be one of this app's clients
leeway=5, # seconds, for a clock a little behind OI's
options={"require": ["sub", "exp", "iat", "jti", "sid"]},
)
if claims.get("azp") not in ALLOWED_CLIENT_IDS:
raise jwt.InvalidTokenError("azp isn't one of this app's clients")
if claims.get("typ") != "Bearer":
raise jwt.InvalidTokenError("not an access token")
if claims.get("service") is True:
raise jwt.InvalidTokenError("a service token, with nobody signed in")
if claims["sid"] in ended_sessions:
raise jwt.InvalidTokenError("the session has ended")
return claimsThe 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.
| Route | OI sends | Your answer | When |
|---|---|---|---|
/internal/ | {"sub": "…", "client_id": "…", "pending_actions": []} | {"allowed": true} lets the person in; anything else keeps them out | On 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/ | {"sids": ["…"], "sub": "…" or null, "ended_at": "…"} | Any 2xx, once you've kept the sids | When someone signs out, or an admin ends their sessions. Without a 2xx, OI tries again for 6 hours. |
/internal/ | {"type": "account.created", "data": {"sub": "…", "email": "…", …}}, signed | Any 2xx, once you've kept the user; 401 for a bad signature | Once 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
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 byaccount.createdor 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>();Where these files go
lib/identity.ts: the webhook secret and signature checks, and the ended sessions.lib/users.ts: this app's users, made byaccount.createdor on the person's first request to/api/me, from OI's userinfo.app/internal/v1/sign-in-check/route.ts,app/internal/v1/session-ends/route.tsandapp/internal/v1/account-created/route.ts: the three routes.
import { createHmac, timingSafeEqual } from 'node:crypto';
/** Whether a call really comes from OI: it sends the webhook secret as a bearer token. */
export function isFromOI(authorization: string | null): 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');
}
/**
* 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: Headers, body: Buffer): boolean {
const secret = process.env.IDENTITY_WEBHOOK_SIGNING_SECRET || process.env.IDENTITY_CALLBACK_TOKEN;
const id = headers.get('webhook-id');
const timestamp = headers.get('webhook-timestamp');
const signatureHeader = headers.get('webhook-signature');
if (!secret || id === null || timestamp === null || signatureHeader === null) {
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), and the account.created deliveries already stored,
// by their webhook-id. Each ended session must stay refused for as long as its access tokens could still work, the
// access token lifetime. In memory suits development only: in production, keep them in Redis or your database. On
// globalThis, as Next.js can load this file more than once.
const globalForIdentity = globalThis as unknown as { endedSessions?: Set<string>; storedDeliveries?: Set<string> };
export const endedSessions = (globalForIdentity.endedSessions ??= new Set<string>());
export const storedDeliveries = (globalForIdentity.storedDeliveries ??= new Set<string>());Where these files go
app/identity_routes.py: the webhook secret and signature checks, the ended sessions, and the three routes, whichapp/main.pyincludes.app/users.py: this app's users, made byaccount.createdor on the person's first request to/api/me, from OI's userinfo.
"""The routes OI calls on this backend. Each is a POST with the webhook secret as a bearer token."""
import base64
import hashlib
import hmac
import json
import os
import time
from collections.abc import Mapping
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from .users import User, upsert_user
# 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.
ended_sessions: set[str] = set()
# 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.
stored_deliveries: set[str] = set()
SIGNATURE_VERSION = "v1"
SIGNING_SECRET_PREFIX = "whsec_"
TOLERANCE_SECONDS = 5 * 60
# One signature per secret in use, so a rotation sends two.
MAX_SIGNATURES = 10
def require_oi(request: Request) -> None:
"""Lets a call through only with OI's webhook secret, compared in constant time. With no secret set, none gets
in."""
secret = os.environ.get("IDENTITY_CALLBACK_TOKEN", "")
sent = request.headers.get("authorization", "")
if not secret or not hmac.compare_digest(sent.encode(), f"Bearer {secret}".encode()):
raise HTTPException(status_code=401, detail="wrong webhook secret")
def read_key(secret: str) -> bytes:
"""A whsec_ signing secret's key is the base64 after the prefix; the webhook secret's, its own UTF-8 bytes."""
if secret.startswith(SIGNING_SECRET_PREFIX):
return base64.b64decode(secret.removeprefix(SIGNING_SECRET_PREFIX))
return secret.encode()
def is_signed_by_oi(headers: Mapping[str, str], body: bytes) -> bool:
"""Whether account.created was signed by OI within TOLERANCE_SECONDS 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."""
secret = os.environ.get("IDENTITY_WEBHOOK_SIGNING_SECRET") or os.environ.get("IDENTITY_CALLBACK_TOKEN", "")
webhook_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signature_header = headers.get("webhook-signature")
if not secret or webhook_id is None or timestamp is None or signature_header is None:
return False
try:
sent_at = int(timestamp) # int() refuses what isn't a number, such as "²", which isdigit() lets through
except ValueError:
return False
if abs(time.time() - sent_at) > TOLERANCE_SECONDS:
return False
entries = signature_header.split(" ")
if len(entries) > MAX_SIGNATURES:
return False
try:
key = read_key(secret)
except ValueError: # a signing secret that isn't whsec_ and base64, such as one copied in part
return False
signed_content = f"{webhook_id}.{timestamp}.".encode() + body
expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest())
signatures = (entry.partition(",") for entry in entries)
return any(
version == SIGNATURE_VERSION and hmac.compare_digest(given.encode(), expected)
for version, _, given in signatures
)
router = APIRouter(prefix="/internal/v1", dependencies=[Depends(require_oi)])
class SignInCheck(BaseModel):
sub: str
client_id: str
pending_actions: list[str] = []
class SessionEnds(BaseModel):
sids: list[str]
sub: str | None = None
ended_at: str
@router.post("/sign-in-check")
async def sign_in_check(body: SignInCheck):
# OI asks on every sign-in, after the password, whether this person may use the app. Anything but
# {"allowed": true} keeps them out. Read-only, and answered within 3 seconds: a real app looks the person up in
# its own database here, such as a blocked account or an unpaid plan, and makes nothing.
print(f"[sign-in-check] {body.sub} on {body.client_id}: allowed")
return {"allowed": True}
@router.post("/session-ends", status_code=204)
async def session_ends(body: SessionEnds):
# OI says which sessions ended, so this app stops letting them in at once instead of when the token expires.
# Answer 2xx once they're kept: OI tries again for 6 hours otherwise.
ended_sessions.update(body.sids)
print(f"[session-ends] {len(body.sids)} session(s)")
return Response(status_code=204)
@router.post("/account-created", status_code=204)
async def account_created(request: Request):
# OI tells this app of a new account, signed. The body is read as raw bytes: the signature is over them as sent.
# Store it once, and answer 2xx as soon as it's stored; a 5xx or no answer is tried again, a 4xx isn't.
body = await request.body()
if not is_signed_by_oi(request.headers, body):
raise HTTPException(status_code=401, detail="bad signature")
delivery_id = request.headers["webhook-id"]
if delivery_id in stored_deliveries:
return Response(status_code=204) # a retry or a replay: already stored
event = json.loads(body)
data = event.get("data") or {}
if event.get("type") == "account.created" and isinstance(data.get("sub"), str):
upsert_user(
User(
sub=data["sub"],
email=data.get("email"),
first_name=data.get("first_name"),
last_name=data.get("last_name"),
language=data.get("language"),
phone_number=data.get("phone_number"),
birthdate=data.get("birthdate"),
)
)
print(f"[account-created] {data['sub']}, {data.get('method')}, sign-up check {data.get('sign_up_check')}")
stored_deliveries.add(delivery_id)
return Response(status_code=204)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
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.tsxandsrc/app/index.tsx: the screens' stack, and the home screen. These replace the blank onesreset-projectmade.src/app/(auth)/sign-in.tsx,sign-up.tsx,verify.tsxandforgot-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);
}Where these files go
lib/auth/token_store.dart: the tokens, in the phone's secure storage with flutter_secure_storage.lib/api/backend.dart: the calls to your backend, the token renewal, and what to tell the person when something is refused.lib/main.dart: the app and its screens, starting on the home screen when someone is signed in. It replaces the starter's.lib/screens/sign_in.dart,sign_up.dart,verify.dart,forgot_password.dartandhome.dart: the screens.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// The tokens, in the phone's secure storage: the Keychain on iOS and the Keystore on Android. Never in
/// shared_preferences, which any code in the app can read and which backups copy.
class TokenStore {
static const _storage = FlutterSecureStorage();
static const _accessToken = 'identity.access_token';
static const _refreshToken = 'identity.refresh_token';
static Future<void> save({required String accessToken, required String refreshToken}) async {
await _storage.write(key: _accessToken, value: accessToken);
await _storage.write(key: _refreshToken, value: refreshToken);
}
static Future<String?> accessToken() => _storage.read(key: _accessToken);
static Future<String?> refreshToken() => _storage.read(key: _refreshToken);
static Future<void> clear() async {
await _storage.delete(key: _accessToken);
await _storage.delete(key: _refreshToken);
}
}Using something else?
| Part | Framework | Where |
|---|---|---|
| Backend | NestJS | A MobileController at mobile that calls OI with fetch, a TokenGuard using jose, and an IdentityController at internal/ |
| Backend | Django | Views in yourapp/ that call OI with httpx, marked @csrf_exempt as the app isn't a browser, and PyJWT's PyJWKClient for the token check |
| Mobile | Swift (iOS) | URLSession for the calls, and the tokens in the Keychain |
| Mobile | Kotlin (Android) | Ktor or Retrofit for the calls, and the tokens encrypted with a key in the Android Keystore |
| Mobile | Ionic or Capacitor | fetch for the calls, and the tokens in a secure-storage plugin, never in localStorage |
Run and check
Start the backend first.
npm run devnpm run dev -- -p 3001uvicorn app.main:app --port 3001 --env-file .env-
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":[]}' -
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 startPress a for the Android emulator or i for the iOS simulator, or scan the QR code with Expo Go.
flutter run --dart-define=BACKEND_URL=http://10.0.2.2:3001On the iOS simulator, use http://localhost:3001.
- Choose Create an account, then type the code OI emails you, then sign in. The backend's log shows
[sign-in-check] … allowed. - Choose Ask the API who I am. The app shows your
sub, the mobile client's ID and your locale. - 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.)
- Choose Sign out. The backend's log shows
[session-ends] 1 session(s). - 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"/>toandroid/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'strust proxy, uvicorn's--proxy-headers), or OI counts everyone's wrong passwords as one person's. Next.js isn't told who connected: setCLIENT_IP_HEADERto the header your host fills in, such asx-real-ipon Vercel, never the left ofx-forwarded-for, which the caller writes. - Limit your own
/mobileroutes 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, answer202all the same, and send that person a forgot-password email instead.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
Sign-in answers 503 unavailable | OI can't reach your backend's sign-in check | Start 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 password | The email isn't verified yet: OI answers as it does for a wrong password, so nobody learns the account exists | Choose 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_incomplete | Your backend put a required action on the account, such as accepting new terms, and it's still to do | Show your own screen for it. Once it's done, your backend calls DELETE / with the API key, and the person signs in again. |
Sign-in answers 403 wrong_application | Your sign-in check answered something other than {"allowed": true} | Check what /internal/ answers for this person. |
Every call to OI answers 401 invalid_api_key | IDENTITY_API_KEY isn't the app's current API key | Copy it again, or rotate it on the app's Security tab and use the new one. |
Sign-up answers 503 mail_server_not_set_up | The app sends email through a mail server that isn't set up | On the app's Email tab, send through OI's mail server, or finish setting up your own. |
/api/ answers 503 unavailable | Your 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/ answers 401 right after signing in | IDENTITY_ALLOWED_CLIENT_IDS isn't the mobile client's ID, or IDENTITY_URL isn't the issuer exactly | Use the values from the Backend section's Copy all, with no trailing slash. |
| The app says Can't reach the server | The phone can't reach the address: localhost on a phone, or on the Android emulator, isn't your computer | Use 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 valid | Links last 10 minutes on a new app | Choose 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.