Skip to Content
Otoko Identity

Server-rendered app

In the wizard: No API that Otoko Identity calls · Web app, server code at sign-in

A website whose pages your server renders, such as Express, Next.js or FastAPI, that needs people signed in and nothing more. Your server does the sign-in and keeps a client secret, which never reaches the browser. Otoko Identity (OI) calls nothing on your side: it runs sign-up, forgot password and invitations on its own pages, and you manage roles in OI's console.

What you'll build

  • /auth/login, which sends people to OI's sign-in page, where they can also Register and use Forgot password.
  • /auth/callback, where OI sends them back and your server swaps the code for tokens with its client secret.
  • A session the browser can't read, and an /account page only a signed-in person sees, with their name, email and roles.
  • /auth/logout, which signs people out of your app and of OI.

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, the callback, a session the browser can't read and sign-out on your server, with its client secret.

Show the full prompt

Connect this server-rendered app's sign-in to Otoko Identity

You are connecting the sign-in of the web app you're working in to Otoko Identity (OI), a standard OpenID Connect provider. The app's own server renders its pages and signs people in with a client secret, which never reaches the browser. It needs people signed in and nothing more: OI calls nothing on its side. Work through the steps below in order, and stop where a step says to wait for the person.

Scope

  • /auth/login, which sends people to OI; /auth/callback, where the server swaps the code for tokens; a session the browser can't read; an /account page only a signed-in person sees, with their name, email and roles; and /auth/logout, which signs people out of the app and of OI.
  • 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 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_CLIENT_SECRET=' .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, Flask or Rails take the same steps), how it runs, its address and port, where its routes live, how it keeps sessions, and any sign-in it already has.
  • Confirm with the person that its server renders the pages and that OI needn't call it. If it should also hear from OI (who may sign in, ended sessions, new accounts) or keep its own users, stop and send them to the prompt on https://identity-docs.otoko.com/quickstarts/server-rendered-app-with-api. If it's a single-page app, send them to https://identity-docs.otoko.com/quickstarts/browser-app.

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 No.
    • 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.
    • Email: leave Send this app's emails through Otoko Identity's mail server ticked, with an optional Reply-to address. Only for an app with its own mail server, 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 section's Copy all, and paste it into the env file you named. It includes the Client secret, for the server only, sent with HTTP Basic authentication at the token endpoint. The client secret and API key are shown only now. This app doesn't use the Server section's API key.
    • Turn on sign-up: a new client starts with it off. Open Apps, the app, the Clients tab and the client, turn on Allow sign-up, and choose Save client.
    • Add a role: on the app's Users & roles tab, set Roles managed by to Admin console, choose Add role, type member, and choose Save changes.
  3. Ask them to tell you when it's done, and wait. Then check the paste by names only.

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, so the app can read roles.
  • APP_URL, where the app runs, such as http://localhost:3000, 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. The code

The connection to OI, read once, such as src/oidc.ts, lib/oidc.ts or app/oidc.py: discovery from IDENTITY_ISSUER (<issuer>/.well-known/openid-configuration), 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:. If discovery fails, ask again next time rather than keep the failure.

The session:

  • Express: express-session, kept on the server, with an httpOnly, SameSite=Lax cookie, secure when APP_URL is https, and proxy: true. The memory store suits development only.
  • Next.js: an iron-session cookie sealed with SESSION_SECRET, httpOnly, SameSite=Lax, secure when APP_URL is https.
  • FastAPI: Starlette's SessionMiddleware with SESSION_SECRET, holding only a random id for the signed-in person, who is kept on the server.
  • It holds the sign-in in progress (PKCE verifier, state and nonce), then the person: access token, ID token, when the access token expires, name, email and roles. currentUser() treats an expired access token as signed out.

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, not on the request's own host.
  • Fetch userinfo with the access token for the name, email and roles. OI's ID token holds only who signed in and how.
  • Start a new session (regenerate its id), store the person, and redirect to /account.
  • On an error, answer 400 with the reason, HTML-escaped, and a link back to /auth/login.

POST /auth/logout: a POST 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 /. Without the ID token, OI won't return the person to the app.

The pages:

  • /: a Sign in link to /auth/login, or, signed in, the email and a link to /account.
  • /account, behind a check that sends anyone not signed in to /auth/login: Hello, and the name (or email), the email, Roles: and the roles (or none), and a form that POSTs to /auth/logout. Escape everything you put in HTML. In Next.js, keep export const instant = false on pages that read the session.

6. Check it works

Run the app (npm run dev, or uvicorn app.main:app --port 3000 --env-file .env) and open http://localhost:3000. You can't sign in for the person, so ask them to:

  1. Choose Sign in, then Register on OI's page, and type the code OI emails. They land on /account, with their name and email.
  2. In the console, give themselves the member role, then sign out and in again. /account says Roles: member.
  3. In the browser's developer tools, see that the session cookie is HttpOnly.
  4. Choose Sign out, then Sign in again. OI asks for their email: its own session ended too.

If OI answers invalid_redirect_uri, IDENTITY_REDIRECT_URI and the client's Valid redirect URIs differ. If the callback fails with invalid_client, the 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, such as a real session store and the live addresses before going live.

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

  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, such as http://localhost:3000/auth/callback. Leave the Sign-out return address as the front page.

  4. Email:

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

  5. Choose Create. On Connect your app, choose the Frontend section's Copy all: it includes the Client secret, sent with HTTP Basic authentication at the token endpoint. The client secret and API key are shown only now. This app doesn't use the Server section's API key.

  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.

Settings

The IDENTITY_ values come from the Frontend section's 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 section (its 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
# 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

Where these files go

auth.ts
oidc.ts
session.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/routes/auth.ts: /auth/login, /auth/callback and /auth/logout.
  • src/server.ts: the app, the front page, and /account behind requireUser.
  • 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;
}

Using something else?

The steps are the same in any server framework: a login route, a callback route that swaps the code with the client secret, a session the browser can't read, and a logout route.

FrameworkConnection to OISessionRoutes
NestJSsrc/auth/oidc.ts, with openid-clientexpress-session, set up in src/main.tsan AuthController in src/auth/auth.controller.ts
Fastifysrc/oidc.ts, with openid-client@fastify/secure-sessiona plugin in src/routes/auth.ts
Djangoyourapp/oidc.py, with Authlib's Django clientDjango's own sessionsyourapp/views.py and yourapp/urls.py
Flaskapp/oidc.py, with Authlib's Flask clientFlask's session, plus a server-side storeapp/auth.py, a blueprint
Railsconfig/initializers/omniauth.rb, with omniauth_openid_connectRails' own sessionsapp/controllers/sessions_controller.rb

Run and check

npm run dev

Open http://localhost:3000.

  1. Choose Sign in. OI's sign-in page opens.
  2. Choose Register, fill in the form, and type the code OI emails you. You land on /account, with your name and email.
  3. In the console, give yourself the member role, then sign out and in again. /account says Roles: member.
  4. In the browser's developer tools, the session cookie is HttpOnly: the page's JavaScript can't read it. With Express and FastAPI it holds only a session ID; with Next.js it holds the session sealed with SESSION_SECRET, which only your server can open.
  5. Choose Sign out, then Sign in again. OI asks for your email: its own session ended too.

When the access token expires, /account sends you to sign in again. While OI's own session is still open, that comes straight back without a password.

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.

If something goes wrong

What you seeWhyWhat to do
OI answers invalid_redirect_uri instead of showing its sign-in pageIDENTITY_REDIRECT_URI isn't on the client's list, exactlyMake it and the client's Valid redirect URIs the same, character for character.
The callback fails with invalid_clientThe client secret is wrong, rotated, or the client's Client authentication is offCopy the current secret from the client's Credentials tab, and check Client authentication is on.
The callback fails about state or nonceThe sign-in started in another browser, or the session cookie was lost on the way backStart again from /auth/login. Check that APP_URL matches the address in the browser, so the cookie is sent back.
FastAPI says InsecureTransportErrorOI is on plain httpOn your own machine, set AUTHLIB_INSECURE_TRANSPORT=1. Use https anywhere else.
Next.js next build stops on / or /accountThe page reads the session while Next.js prerenders itKeep export const instant = false on pages that read the session.
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 isn't in the scopes, the person has no role yet, or they haven't signed in since getting itAdd roles to IDENTITY_SCOPES, give the role in the console, 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.