Server-rendered app + API
In the wizard: An API that Otoko Identity calls · Web app, server code at sign-in
A full-stack app, such as Express, Next.js or FastAPI, where one server renders the pages and is also the backend Otoko Identity (OI) calls. Your server signs people in with its client secret, and answers OI on every sign-in: whether this person may use your app. OI also tells it when a session ends, so it can stop letting that person in at once.
What you'll build
/auth/login,/auth/callbackand/auth/logout: sign-in and sign-out, with a session the browser can't read./account, a page only a signed-in person sees, with their name, email and roles./internal/v1/sign-in-check,/internal/v1/session-endsand the signed/internal/v1/account-created: the three routes OI calls on your backend.- This app's own users, made by
account.createdor when the person first signs in here.
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 web app's project. It tells you what to register on the console, then writes sign-in and sign-out on your server, the routes Otoko Identity calls, and your own users.
Show the full prompt
Connect this server-rendered app to Otoko Identity, as its sign-in and its backend
You are connecting the full-stack web app you're working in to Otoko Identity (OI), a standard OpenID Connect provider. One server renders the pages, signs people in with a client secret, and is also the backend OI calls: on every sign-in, to ask whether this person may use the app; when a session ends, so it stops letting them in at once; 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
/auth/login,/auth/callbackand/auth/logout, with a session the browser can't read, and an/accountpage only a signed-in person sees, with their name, email and roles.- The three routes OI calls:
/internal/v1/sign-in-check,/internal/v1/session-endsand the signed/internal/v1/account-created. - The app's own users, made by
account.createdor when the person first signs in here. - OI runs sign-up, forgot password and invitations on its own pages, and roles are managed on OI's console. Don't build them.
- Change nothing unrelated to signing in.
Rules
- The client secret, the webhook secret, the signing secret and
SESSION_SECRETlive only in an env file that 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_CALLBACK_TOKEN=' .env). - Never put a secret in browser code, a log line or a commit.
- 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
- Use a maintained OpenID Connect library: openid-client on a Node server, Authlib in Python, or the established one for the project's stack. Never write the flow by hand.
- Never let the page's JavaScript see the tokens: the browser gets only the session cookie.
- Use https everywhere outside a local machine.
1. Look at the project
- Find its framework (Express, Next.js with the App Router, and FastAPI are the worked examples; NestJS, Fastify, Django or Rails take the same steps), how it runs, its address and port, where its routes live, how it keeps sessions, its sign-in middleware and CSRF protection, where it keeps users, and any sign-in it already has.
- Confirm with the person that its server renders the pages and should hear from OI. If it only needs people signed in, stop and send them to the prompt on https://identity-docs.otoko.com/quickstarts/server-rendered-app. If it's a single-page app, send them to https://identity-docs.otoko.com/quickstarts/browser-app-with-api.
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 env file the settings go in:
.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.
- How people sign in: choose Web app, and to Does your app run server code when someone signs in? leave Yes. Type the App address, such as
http://localhost:3000. Open Advanced and change the Sign-in return address to the address plus/auth/callback. Leave the Sign-out return address as the front page. - Backend and email: type the Backend address, where OI reaches this server: the same as the app address. With OI running in Docker on the same machine, that's
http://host.docker.internal:3000, 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 Frontend and Backend sections' own Copy all, and paste both into the env file you named. The Frontend section has the Client secret, for the server only, sent with HTTP Basic authentication at the token endpoint, and the Backend section the webhook secret (
IDENTITY_CALLBACK_TOKEN). The client secret, API key and webhook secret are shown only now. - Turn on sign-up: open Apps, the app, the Clients tab and the client, turn on Allow sign-up, and choose Save client.
- Add a role: on the Users & roles tab, set Roles managed by to Admin console (an app with a backend starts on Application backend), choose Add role, type
member, and choose Save changes. - 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 this server on every sign-in: until it runs and answers /internal/v1/sign-in-check, nobody can sign in.
3. Settings
The code reads these, from the env file:
IDENTITY_ISSUER,IDENTITY_CLIENT_ID,IDENTITY_CLIENT_SECRET,IDENTITY_REDIRECT_URIandIDENTITY_SCOPES, from the Frontend section's Copy all. AddrolestoIDENTITY_SCOPES(such asopenid profile email roles), editing only that line.IDENTITY_CALLBACK_TOKEN, the webhook secret, andIDENTITY_WEBHOOK_SIGNING_SECRET, empty until the app has one. The Backend section also givesIDENTITY_URL,IDENTITY_APP_ID,IDENTITY_API_KEYandIDENTITY_ALLOWED_CLIENT_IDS, which this app doesn't use: leave them be.APP_URL, where the app runs, andSESSION_SECRET, a long random string of at least 32 characters. Both are the app's own: add them, generating the secret into the file without printing it.- For FastAPI with a local OI on plain http only,
AUTHLIB_INSECURE_TRANSPORT=1. Never with https.
Add an .env.example with the same names and placeholder values.
4. Install
- Express:
express express-session openid-client, withtypescript tsx @types/express @types/express-session @types/nodeas dev dependencies. The examples are ES modules ("type": "module"). - Next.js:
openid-client iron-session. - FastAPI:
fastapi,uvicorn[standard],authlib,httpx,itsdangerousandpython-dotenv.
5. Sign-in and sign-out
The connection to OI, read once: discovery from IDENTITY_ISSUER, IDENTITY_CLIENT_ID, and IDENTITY_CLIENT_SECRET sent as HTTP Basic, the console's default. With openid-client, allow plain http only when the issuer is http:.
The session: express-session kept on the server (with proxy: true), an iron-session cookie sealed with SESSION_SECRET in Next.js, or Starlette's SessionMiddleware holding only a random id in FastAPI. The cookie is httpOnly, SameSite=Lax, and secure when APP_URL is https. It holds the sign-in in progress (PKCE verifier, state and nonce), then the person: access token, ID token, when the access token expires, OI's session id sid, name, email and roles. currentUser() treats as signed out a person whose access token has expired or whose sid is among the ended sessions.
GET /auth/login: keeps a new PKCE verifier, state and nonce in the session, and redirects to OI's authorization endpoint with IDENTITY_REDIRECT_URI, IDENTITY_SCOPES, the S256 code challenge, the state and the nonce.
GET /auth/callback:
- With no sign-in in progress, redirect to
/auth/login. - Swap the code with the PKCE verifier and the client secret; the library checks the state, the nonce and the ID token. Build the callback URL on
APP_URL. - Fetch userinfo with the access token for the name, email and roles.
- Make this app's user if there's none, keyed by
sub, never by email, from userinfo'semail,given_name,family_nameandlocale: an insert that ignores a conflict. - Read
sidfrom the access token's payload (the library has already checked the tokens), start a new session, store the person with it, and redirect to/account. - On an error, answer 400 with the reason, HTML-escaped, and a link back to
/auth/login.
POST /auth/logout: from the app's own pages only: refuse with 403 when Sec-Fetch-Site is present and not same-origin, or, without it, when Origin is present and isn't APP_URL's origin. Read the ID token, destroy the session, and redirect (303) to OI's end-session endpoint with id_token_hint and post_logout_redirect_uri set to APP_URL plus /.
The pages: / with a Sign in link, or the email and a link to /account; /account, sending anyone not signed in to /auth/login, with Hello, and the name, the email, Roles: and the roles (or none), and a form that POSTs to /auth/logout. Escape what goes in HTML. In Next.js, keep export const instant = false on pages that read the session.
6. 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 sessionscurrentUser()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"make the user fromdata(sub,email,first_name,last_name,language; names may be null) with the same insert as the callback, log[account-created] <sub>, <method>, …, store thewebhook-id, and answer 204.
OI calls these server to server, with no cookies: keep them out of the app's sign-in middleware and CSRF protection, or every sign-in fails. The examples keep the sessions, the ended sessions, the webhook ids and the users in memory; say in your report that production needs a real store.
7. Check it works
Run the app (npm run dev, or uvicorn app.main:app --port 3000 --env-file .env).
- A POST to
/internal/v1/sign-in-checkwith no bearer token, such ascurl -i -X POST http://localhost:3000/internal/v1/sign-in-check -H "Content-Type: application/json" -d '{"sub":"x","client_id":"x","pending_actions":[]}', must answer 401.
Then open http://localhost:3000 and ask the person to:
- Choose Sign in, then Register, and type the code OI emails. The app's log shows
[sign-in-check] … allowedand[account-created] …, password, …, and they land on/account. - In the console, give themselves the
memberrole, then sign out and in again./accountsays Roles: member. - Choose Sign out. The log shows
[session-ends] 1 session(s). - Sign in again, then in the console open Sessions and choose Sign out beside their session. Reloading
/accountsends them to sign in, though the access token hadn't expired.
If OI's sign-in page says Sign-in isn't available right now, OI can't reach the sign-in check: check the backend address. If the callback fails with invalid_client, the client secret is wrong or rotated. For other errors, read https://identity-docs.otoko.com/troubleshooting.
Finish with a short report: the files you changed, the routes and pages 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/server-rendered-app-with-api: this setup, step by step, with Express, Next.js and FastAPI code.
- https://identity-docs.otoko.com/api-reference/calls-to-your-backend: every route OI calls, and verifying the signature.
- https://identity-docs.otoko.com/api-reference/openid-connect: the flow, endpoints and scopes.
- 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.
-
How people sign in: choose Web app, and to Does your app run server code when someone signs in? leave Yes. Type the App address, such as
http://localhost:3000. Open Advanced and change the Sign-in return address to the address plus/auth/callback. Leave the Sign-out return address as the front page. -
Backend and email: type the Backend address, where OI reaches your server: the same as the app address here. With OI running in Docker on your own machine, that's
http://host.docker.internal:3000, 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, use the Frontend and Backend sections' own Copy all, both into the server's env file: the Frontend section includes the Client secret, sent with HTTP Basic authentication at the token endpoint, and the Backend section the webhook secret (
IDENTITY_CALLBACK_TOKEN). The client secret, API key and webhook secret are shown only now. -
Turn on sign-up. A new client starts with it off, and until it's on, OI's sign-in page shows no Register link. Open Apps, your app, the Clients tab, and your client. Turn on Allow sign-up, then choose Save client. (The app's own Sign-up allowed and Forgot password, under Login on its Overview tab, are on for a new app.)
-
Add a role. On the app's Users & roles tab, set Roles managed by to Admin console (an app with a backend starts on Application backend), choose Add role, type
member, and choose Save changes. Once someone has signed up, give them the role with the pencil button in their Roles column in the users list. Your app asks for therolesscope to read them. -
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 your app is running and answers /internal/v1/sign-in-check, nobody can sign in.
Settings
The IDENTITY_ values come from the two sections' Copy all, with roles added to the scopes. APP_URL and SESSION_SECRET are your own: make the secret a long random string. The file holds secrets, so keep it out of git.
Copy .env.example to .env.
# Copy to .env. The IDENTITY_ values come from Connect an app's Frontend and Backend sections (each Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# The webhook secret: OI sends it on every call to this backend. The Backend section also gives IDENTITY_URL, IDENTITY_APP_ID,
# IDENTITY_API_KEY and IDENTITY_ALLOWED_CLIENT_IDS, which this app doesn't need.
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: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-charactersCopy .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 Frontend and Backend sections (each Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# The webhook secret: OI sends it on every call to this backend. The Backend section also gives IDENTITY_URL, IDENTITY_APP_ID,
# IDENTITY_API_KEY and IDENTITY_ALLOWED_CLIENT_IDS, which this app doesn't need.
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: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-charactersCopy .env.example to .env. With OI on plain http on your own machine, add AUTHLIB_INSECURE_TRANSPORT=1, as Authlib refuses http otherwise. Never set it with https.
# Copy to .env. The IDENTITY_ values come from Connect an app's Frontend and Backend sections (each Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# The webhook secret: OI sends it on every call to this backend. The Backend section also gives IDENTITY_URL, IDENTITY_APP_ID,
# IDENTITY_API_KEY and IDENTITY_ALLOWED_CLIENT_IDS, which this app doesn't need.
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: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-characters
# Only for a local OI on plain http (Authlib refuses http otherwise). Leave it out with https.
# AUTHLIB_INSECURE_TRANSPORT=1Install
A new app. For an app 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-app && cd my-app
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 express-session openid-client
npm install -D typescript tsx @types/express @types/express-session @types/nodeA new app (skip the first two lines for an app you already have):
npx create-next-app@latest my-app --ts --app --eslint --yes --no-src-dir --import-alias "@/*"
cd my-app
npm install openid-client iron-sessionA new app, with Python 3.10 or later. First save this as requirements.txt:
fastapi
uvicorn[standard]
authlib
httpx
itsdangerous
python-dotenvThen:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install -r requirements.txtAdd the code
Sign-in and sign-out
Where these files go
src/oidc.ts: the connection to OI, read once.src/session.ts: the session, kept on the server, with what it holds.src/users.ts: this app's users, made byaccount.createdor when the person first signs in here.src/routes/auth.ts:/auth/login,/auth/callbackand/auth/logout. The callback makes the person's user from OI's userinfo if there's none yet, and keeps the session'ssid, which OI names when the session ends.src/server.ts: the app, the front page,/accountbehindrequireUser, and OI's routes under/internal/v1.tsconfig.json: fornpm run typecheck.tsxruns the code without a build step.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this server is the app.
*/
export function getOidcConfig(): Promise<client.Configuration> {
const issuer = new URL(process.env.IDENTITY_ISSUER!);
config ??= client
.discovery(
issuer,
process.env.IDENTITY_CLIENT_ID!,
undefined,
client.ClientSecretBasic(process.env.IDENTITY_CLIENT_SECRET!),
// Only for a local OI on plain http. Leave it out with https.
issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined,
)
.catch((error: unknown) => {
config = undefined; // ask again next time, rather than keep the failure
throw error;
});
return config;
}Where these files go
lib/oidc.ts: the connection to OI, read once.lib/session.ts: the session, as a sealed cookie, andcurrentUser(), which also refuses an ended session.lib/users.ts: this app's users, made byaccount.createdor when the person first signs in here.app/auth/login/route.ts,app/auth/callback/route.tsandapp/auth/logout/route.ts: the three routes. The callback makes the person's user from OI's userinfo if there's none yet, and keeps the session'ssid.app/page.tsxandapp/account/page.tsx: the front page, and a page only a signed-in person sees.app/page.tsxreplaces the starter's.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this server is the app.
*/
export function getOidcConfig(): Promise<client.Configuration> {
const issuer = new URL(process.env.IDENTITY_ISSUER!);
config ??= client
.discovery(
issuer,
process.env.IDENTITY_CLIENT_ID!,
undefined,
client.ClientSecretBasic(process.env.IDENTITY_CLIENT_SECRET!),
// Only for a local OI on plain http. Leave it out with https.
issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined,
)
.catch((error: unknown) => {
config = undefined; // ask again next time, rather than keep the failure
throw error;
});
return config;
}Where these files go
app/oidc.py: the connection to OI, through Authlib.app/sessions.py: the signed-in people, kept on the server.app/users.py: this app's users, made byaccount.createdor when the person first signs in here.app/main.py: the app, the three/authroutes, the front page,/account, and OI's routes. The callback makes the person's user from OI's userinfo if there's none yet.
"""Otoko Identity, through Authlib. It reads OI's discovery document, and signs in with PKCE, a state and a nonce."""
import os
from authlib.integrations.starlette_client import OAuth
oauth = OAuth()
oauth.register(
name="identity",
server_metadata_url=f"{os.environ['IDENTITY_ISSUER']}/.well-known/openid-configuration",
client_id=os.environ["IDENTITY_CLIENT_ID"],
client_secret=os.environ["IDENTITY_CLIENT_SECRET"], # sent as HTTP Basic, the console's default
client_kwargs={"scope": os.environ["IDENTITY_SCOPES"], "code_challenge_method": "S256"},
)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.account-createdkeeps the new person's user withsrc/users.ts.
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.app/internal/v1/sign-in-check/route.ts,app/internal/v1/session-ends/route.tsandapp/internal/v1/account-created/route.ts: the three routes.account-createdkeeps the new person's user withlib/users.ts.
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 this file goes
app/identity_routes.py: the webhook secret and signature checks, the ended sessions, and the three routes, whichapp/main.pyincludes.account-createdkeeps the new person's user withapp/users.py.
"""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)Using something else?
| Framework | Sign-in | OI's routes |
|---|---|---|
| NestJS | openid-client in src/, with express-session | an IdentityController at internal/, behind a guard that checks the webhook secret |
| Fastify | openid-client, with @fastify/ | a plugin with the three routes, and a preHandler that checks the secret |
| Django | Authlib's Django client in yourapp/ | three views in yourapp/, marked @csrf_exempt, as OI isn't a browser |
| Rails | omniauth_openid_connect | Internal::V1::IdentityController, skipping the CSRF check for these three routes |
Run and check
npm run devnpm run devuvicorn app.main:app --port 3000 --env-file .envOpen http://localhost:3000.
-
Before signing in, check the backend's door is locked. This must answer
401:curl -i -X POST http://localhost:3000/internal/v1/sign-in-check -H "Content-Type: application/json" -d '{"sub":"x","client_id":"x","pending_actions":[]}' -
Choose Sign in, then Register, and type the code OI emails you. Your app's log shows
[sign-in-check] … allowed, and[account-created] …, password, …as OI tells it of the new account, and you land on/account. -
In the console, give yourself the
memberrole, then sign out and in again./accountsays Roles: member. -
Choose Sign out. Your app's log shows
[session-ends] 1 session(s). -
Sign in again, then in the console open Sessions and choose Sign out beside your session. Reload
/account: your app sends you to sign in, though the access token hadn't expired.
Before going live
- Use https for your app and for Otoko Identity. Only
localhostmay use http. The session cookie then getsSecure, fromAPP_URL. - Add your live addresses to the client, on its page in the console: the callback under Valid redirect URIs and the front page under Valid post-logout redirect URIs. They're compared exactly, character for character.
- Keep the client secret and
SESSION_SECRETout of git, in your host's secret settings. A leaked client secret is replaced on the client's Credentials tab; the old one keeps working for 24 hours, or stops at once if you say so. - Express and FastAPI: keep sessions in a real store (Redis, or your database) rather than in memory, so a restart or a second server doesn't sign everyone out. Next.js's sealed cookie needs no store.
- Never let the page's JavaScript see the tokens. The browser gets only the session cookie, which it can't read.
- Behind a proxy or a load balancer that ends https, as most hosts are, the code works as it is: the Express session trusts the proxy's
X-Forwarded-Protofor its cookie (proxy: true), and the Next.js routes build every address onAPP_URL, not on the address the request came in on.
- Give OI your backend's live address on the app's Overview tab, over https.
- Keep ended sessions in a real store, each with the access token lifetime as its expiry, so every server refuses them.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
| OI's sign-in page says Sign-in isn't available right now, please try again shortly. | OI can't reach your backend's sign-in check | Start your app first. Check the Backend address: with OI in Docker, use host.docker.internal, not localhost. |
Your app's log shows 401 for /internal/ | IDENTITY_CALLBACK_TOKEN isn't the app's webhook secret | Copy the secret again, or set a new one on the app's Security tab. |
The app's Webhook deliveries shows account.created dead with 401 | The signature didn't match: IDENTITY_WEBHOOK_SIGNING_SECRET isn't the app's current signing secret, or it's unset since the app got one | Copy it again, or make a new one on the app's Security tab. Then Replay the dead deliveries on the app's Webhook deliveries. |
The callback fails with invalid_client | The client secret is wrong, rotated, or Client authentication is off | Copy the current secret from the client's Credentials tab, and check Client authentication is on. |
| A signed-out person still gets in until the token expires | /internal/ didn't answer 2xx, or the app checks a different store | Check your app's log for the call, and that the page's check reads the same store the route writes. |
| OI's sign-in page has no Register link | Allow sign-up is off on the client, or Sign-up allowed is off on the app | Turn them on, as in step 1. |
| Roles: none | Roles managed by is still Application backend, roles isn't in the scopes, or the person signed in before getting the role | Switch it to Admin console, add roles to the scopes, give the role, and sign in again. |
Tested with Express 5.3.0, express-session 1.19.0, tsx 4.23.15 · Next.js 16.4.6, iron-session 9.1.0 · openid-client 6.9.0 · FastAPI 0.165.0, Authlib 1.9.9, uvicorn 0.54.0, Python 3.14.