Skip to Content
Otoko Identity

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/callback and /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-ends and the signed /internal/v1/account-created: the three routes OI calls on your backend.
  • This app's own users, made by account.created or 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.

Agent prompt

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/callback and /auth/logout, with a session the browser can't read, and an /account page 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-ends and the signed /internal/v1/account-created.
  • The app's own users, made by account.created or 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_SECRET live 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.
  • 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.

  1. Name the env file the settings go in: .env, or .env.local for Next.js. Check that git ignores it before anything is pasted, and add it to .gitignore if not.
  2. Tell the person to open https://identity.otoko.com/admin/apps/new and:
    • Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes.
    • 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, not localhost. Leave Send this app's emails through Otoko Identity's mail server ticked, unless the app has its own mail server: then they untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat.
    • Choose Create, then on Connect your app the 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 as IDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
  3. Ask them to tell you when it's done, and wait. Then check the paste by names only.

From then on, OI asks 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_URI and IDENTITY_SCOPES, from the Frontend section's Copy all. Add roles to IDENTITY_SCOPES (such as openid profile email roles), editing only that line.
  • IDENTITY_CALLBACK_TOKEN, the webhook secret, and IDENTITY_WEBHOOK_SIGNING_SECRET, empty until the app has one. The Backend section also gives IDENTITY_URL, IDENTITY_APP_ID, IDENTITY_API_KEY and IDENTITY_ALLOWED_CLIENT_IDS, which this app doesn't use: leave them be.
  • APP_URL, where the app runs, and SESSION_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, with typescript tsx @types/express @types/express-session @types/node as dev dependencies. The examples are ES modules ("type": "module").
  • Next.js: openid-client iron-session.
  • FastAPI: fastapi, uvicorn[standard], authlib, httpx, itsdangerous and python-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's email, given_name, family_name and locale: an insert that ignores a conflict.
  • Read sid from 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>: allowed and answer {"allowed": true}. Leave a comment that a real app checks its own records here, such as a blocked account or an unpaid plan. Keep it read-only and fast (OI waits 3 seconds), and make no user here. Anything other than {"allowed": true} keeps the person out.
  • session-ends: the body is {"sids": [...], "sub": "..." or null, "ended_at": "..."}. Answer 400 unless sids is a list of strings. Store each sid among the ended sessions currentUser() reads, log [session-ends] <n> session(s), and answer 204. Without a 2xx, OI tries again for 6 hours.
  • account-created: read the raw body bytes, before any JSON parsing. Verify the Standard Webhooks signature: base64 of HMAC-SHA256 over webhook-id, a dot, webhook-timestamp, a dot, then the body. The key is IDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes after whsec_; when that's empty, it's IDENTITY_CALLBACK_TOKEN's own UTF-8 bytes. webhook-signature may hold several v1, entries separated by spaces: refuse more than 10, and accept any that matches, compared in constant time. Answer 401 to a missing header, a bad signature, or a webhook-timestamp that isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to a webhook-id already stored. Otherwise parse the body, and for "type": "account.created" make the user from data (sub, email, first_name, last_name, language; names may be null) with the same insert as the callback, log [account-created] <sub>, <method>, …, store the webhook-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-check with no bearer token, such as 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":[]}', must answer 401.

Then open http://localhost:3000 and ask the person to:

  1. Choose Sign in, then Register, and type the code OI emails. The app's log shows [sign-in-check] … allowed and [account-created] …, password, …, and they land on /account.
  2. In the console, give themselves the member role, then sign out and in again. /account says Roles: member.
  3. Choose Sign out. The log shows [session-ends] 1 session(s).
  4. Sign in again, then in the console open Sessions and choose Sign out beside their session. Reloading /account sends 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

Register the app

  1. In the console, open Connect an app.

  2. Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes.

  3. 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.

  4. 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, not localhost. Then, for the emails:

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

  5. Choose Create. On Connect your app, 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.

  6. 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.)

  7. 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 the roles scope to read them.

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

Warning

From now on, OI asks your backend on every sign-in. Until 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.

.env.example
# 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

Install

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/node

Add the code

Sign-in and sign-out

Where these files go

auth.ts
oidc.ts
session.ts
users.ts
server.ts
tsconfig.json
  • 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 by account.created or when the person first signs in here.
  • src/routes/auth.ts: /auth/login, /auth/callback and /auth/logout. The callback makes the person's user from OI's userinfo if there's none yet, and keeps the session's sid, which OI names when the session ends.
  • src/server.ts: the app, the front page, /account behind requireUser, and OI's routes under /internal/v1.
  • tsconfig.json: for npm run typecheck. tsx runs 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;
}

The routes Otoko Identity calls

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

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

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

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

Where these files go

identity.ts
identity.ts
  • src/identity.ts: the webhook secret and signature checks, and the ended sessions.
  • src/routes/identity.ts: the three routes, under /internal/v1. account-created keeps the new person's user with src/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>();

Using something else?

FrameworkSign-inOI's routes
NestJSopenid-client in src/auth/, with express-sessionan IdentityController at internal/v1, behind a guard that checks the webhook secret
Fastifyopenid-client, with @fastify/secure-sessiona plugin with the three routes, and a preHandler that checks the secret
DjangoAuthlib's Django client in yourapp/oidc.pythree views in yourapp/identity_views.py, marked @csrf_exempt, as OI isn't a browser
Railsomniauth_openid_connectInternal::V1::IdentityController, skipping the CSRF check for these three routes

Run and check

npm run dev

Open http://localhost:3000.

  1. 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":[]}'
  2. 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.

  3. In the console, give yourself the member role, then sign out and in again. /account says Roles: member.

  4. Choose Sign out. Your app's log shows [session-ends] 1 session(s).

  5. 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 localhost may use http. The session cookie then gets Secure, from APP_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_SECRET out 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-Proto for its cookie (proxy: true), and the Next.js routes build every address on APP_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 seeWhyWhat 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 checkStart 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/v1/sign-in-checkIDENTITY_CALLBACK_TOKEN isn't the app's webhook secretCopy the secret again, or set a new one on the app's Security tab.
The app's Webhook deliveries shows account.created dead with 401The signature didn't match: IDENTITY_WEBHOOK_SIGNING_SECRET isn't the app's current signing secret, or it's unset since the app got oneCopy 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_clientThe client secret is wrong, rotated, or Client authentication is offCopy 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/v1/session-ends didn't answer 2xx, or the app checks a different storeCheck 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 linkAllow sign-up is off on the client, or Sign-up allowed is off on the appTurn them on, as in step 1.
Roles: noneRoles managed by is still Application backend, roles isn't in the scopes, or the person signed in before getting the roleSwitch 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.