Browser app + API
In the wizard: An API that Otoko Identity calls · Web app, no server code at sign-in
A single-page app (SPA), such as React, Vue or Angular, that calls an API of yours on another address. The browser signs people in with PKCE and no secret, then sends the access token to your API with each call. Your API checks the token, and is also the backend Otoko Identity (OI) calls: on every sign-in, and when a session ends.
What you'll build
- The front end: the front-end-only setup, plus a button that calls your API with the person's access token.
- The API: a token check, a protected
GET /api/methat makes the person's user on their first request, CORS for your front end's address, and the three routes OI calls,/internal/v1/sign-in-check,/internal/v1/session-endsand the signed/internal/v1/account-created.
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 single-page app's and API's project. It tells you what to register on the console, then writes sign-in in the browser, the token check and a first-request user in your API, and the routes Otoko Identity calls.
Show the full prompt
Connect this browser app and its API to Otoko Identity
You are connecting a single-page app (SPA) and the API it calls, on another address, to Otoko Identity (OI), a standard OpenID Connect provider. The browser signs people in with PKCE and no secret, and sends the access token to the API with each call. The API checks the token, and is also the backend OI calls: on every sign-in, when a session ends, and when an account is made. Work through the steps below in order, and stop where a step says to wait for the person.
Scope
- The front end: a Sign in button, a
/callbackroute, a front page with the signed-in person's name, email and roles, a button that calls the API with the access token, and Sign out. - The API: the token check, a protected
GET /api/methat makes the person's user on their first request, CORS for the front end's address, and the three routes OI calls:/internal/v1/sign-in-check,/internal/v1/session-endsand the signed/internal/v1/account-created. - 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 front end has no secrets. The webhook secret, the signing secret and the API key live only in the API's env file, which git ignores.
- Never open, print or paste the whole env file, and never ask for a secret in the chat. To check a setting is there, look for its name only (for example
grep -c '^IDENTITY_CALLBACK_TOKEN=' .env). - Never put a secret in browser code, a log line or a commit, and never expose the API's settings to the browser.
- 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
- In the browser, use oidc-client-ts, and keep the tokens where it puts them, in sessionStorage, never in localStorage. In the API, use a maintained JWT library, such as jose for Node or PyJWT for Python. Never write the flow or the token checks by hand.
- Use https everywhere outside a local machine.
1. Look at the project
- Find the front end's framework (React, Vue and Angular are the worked examples), its dev address (Vite's is
http://localhost:5173, Angular'shttp://localhost:4200), and the API's framework (Express, Next.js route handlers and FastAPI are the worked examples; NestJS, Fastify, Django REST Framework or Spring Boot take the same steps), its port (the examples use 3001), and any sign-in middleware or CSRF protection it has. If the API isn't in this project, ask where it is. - Confirm with the person that the browser signs in and calls the API. If the server renders the pages, stop and send them to https://identity-docs.otoko.com/quickstarts/server-rendered-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 API's env file:
.env, or.env.localfor Next.js. Check that git ignores it before anything is pasted, and add it to.gitignoreif not. - Tell the person to open https://identity.otoko.com/admin/apps/new and:
- Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes.
- How people sign in: choose Web app, and to Does your app run server code when someone signs in? answer No: the browser swaps the code for tokens, and the API never does. Type the App address, the front end's. Open Advanced and change the Sign-in return address to the address plus
/callback. Leave the Sign-out return address as the front page. - Backend and email: type the Backend address, the API's, such as
http://localhost:3001. With OI running in Docker on the same machine, that'shttp://host.docker.internal:3001, notlocalhost. Leave Send this app's emails through Otoko Identity's mail server ticked, unless the app has its own mail server: then they untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat. - Choose Create, then on Connect your app each section's own Copy all. Paste the Backend section's values (
IDENTITY_URL,IDENTITY_APP_ID,IDENTITY_ALLOWED_CLIENT_IDS,IDENTITY_CALLBACK_TOKENand the API key) into the API's env file only. The API key and webhook secret are shown only now. The Frontend section's values aren't secret: they give them to you for the front end. - 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, 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 API's env file asIDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
- Ask them to tell you when it's done, and wait. Then check the API's env by names only.
From then on, OI asks the API on every sign-in: until the API runs and answers /internal/v1/sign-in-check, nobody can sign in.
3. Settings
The front end (built into the page, none secret; add roles to the scopes):
- Vite:
.env.localwithVITE_IDENTITY_ISSUER,VITE_IDENTITY_CLIENT_ID,VITE_IDENTITY_REDIRECT_URI,VITE_IDENTITY_SCOPES(such asopenid profile email roles) andVITE_API_URL, the API's address. - Angular:
src/environments/environment.tswithidentity: { issuer, clientId, redirectUri, scopes }andapiUrl.
The API: IDENTITY_URL, IDENTITY_ALLOWED_CLIENT_IDS (comma-separated), IDENTITY_CALLBACK_TOKEN and IDENTITY_WEBHOOK_SIGNING_SECRET, plus its own FRONT_END_ORIGINS, the front end's address or several separated by commas, with no trailing slash, and PORT=3001. Add an .env.example with the same names and placeholder values.
4. Install
- Front end:
oidc-client-ts, plusreact-router-dom(React) orvue-router(Vue) if there's no router yet. - API: Express
express jose cors(dev:typescript tsx @types/express @types/cors @types/node); Next.jsjose; FastAPIfastapi,uvicorn[standard],pyjwt[crypto]>=2.14,httpxandpython-dotenv.
5. The front end
- The connection to OI, such as
src/auth/oidc.ts: aUserManagerwithauthorityset to the issuer,client_id,redirect_uri,post_logout_redirect_uriset to the app's origin plus/,scope,loadUserInfo: trueandautomaticSilentRenew: false.signIn()callssigninRedirect({ nonce: crypto.randomUUID() });signOut()callssignoutRedirect(). - The signed-in person, shared by every component:
getUser()at start, an expired user is signed out, and follow theuserLoaded,userUnloadedandaccessTokenExpiredevents. /callback: callsigninRedirectCallback()once, then go to/withreplace. On an error, go to/if someone is signed in, or show it with Try again.- The API call, such as
src/api.ts:callApi(path)sendsAuthorization: Bearer <access token>to the API's address. With no user, or an expired one, it says to sign in first. On a 401, it callsremoveUser(), so the page offers Sign in again. - The front page: Sign in, or, signed in, the name, email and roles, an Ask the API who I am button that shows
GET /api/me's answer, and Sign out.
6. The API
The token check, such as verifyAccessToken() in src/token.ts. Answer 401 with WWW-Authenticate: Bearer to a missing or failing token:
- ES256 only, with keys from
IDENTITY_URLfollowed by/.well-known/jwks.json, cached by the library, andissequal toIDENTITY_URL. audandazpboth amongIDENTITY_ALLOWED_CLIENT_IDS.- The
typclaim in the token's payload isBearer. It's a claim, not the JWT header'styp: with jose, check it among the claims, not with thetypoption. sub,exp,iat,jtiandsidall present. Refuse a token with"service": true, and one whosesidis among the ended sessions.- When OI's keys can't be fetched at all (not a token naming an unknown key), answer 503
{"error": "unavailable"}: the token may be fine.
GET /api/me, behind the token check, with CORS for FRONT_END_ORIGINS only, allowing the Authorization header (answer the browser's OPTIONS preflight too). Look the user up by sub. If there's none, call IDENTITY_URL followed by /oauth/userinfo with the same access token, and upsert the user keyed by sub, never by email, from email, given_name, family_name and locale, allowing for missing names. A 401 from userinfo answers 401; userinfo unreachable or failing answers 503. Answer {"sub", "email", "client": <azp>, "locale"}.
The routes OI calls, under /internal/v1, with no CORS. Each first checks Authorization: Bearer <IDENTITY_CALLBACK_TOKEN> in constant time, and answers 401 to anything else, or to every call when the setting is unset.
POST /internal/v1/sign-in-check
Authorization: Bearer <IDENTITY_CALLBACK_TOKEN>
Content-Type: application/json
{ "sub": "5b1c6f0e-0000-4000-8000-000000000000", "client_id": "your-client-id", "pending_actions": [] }
HTTP/1.1 200 OK
Content-Type: application/json
{ "allowed": true }sign-in-check: log[sign-in-check] <sub> on <client_id>: allowedand answer{"allowed": true}. Leave a comment that a real app checks its own records here, such as a blocked account or an unpaid plan. Keep it read-only and fast (OI waits 3 seconds), and make no user here. Anything other than{"allowed": true}keeps the person out.session-ends: the body is{"sids": [...], "sub": "..." or null, "ended_at": "..."}. Answer 400 unlesssidsis a list of strings. Store eachsidamong the ended sessions the token check reads, log[session-ends] <n> session(s), and answer 204. Without a 2xx, OI tries again for 6 hours.account-created: read the raw body bytes, before any JSON parsing. Verify the Standard Webhooks signature: base64 of HMAC-SHA256 overwebhook-id, a dot,webhook-timestamp, a dot, then the body. The key isIDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes afterwhsec_; when that's empty, it'sIDENTITY_CALLBACK_TOKEN's own UTF-8 bytes.webhook-signaturemay hold severalv1,entries separated by spaces: refuse more than 10, and accept any that matches, compared in constant time. Answer 401 to a missing header, a bad signature, or awebhook-timestampthat isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to awebhook-idalready stored. Otherwise parse the body, and for"type": "account.created"upsert the user fromdata(sub,email,first_name,last_name,language; names may be null), keyed bysubas above, 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 API's sign-in middleware and CSRF protection, or every sign-in fails. The examples keep the ended sessions, the webhook ids and the users in memory; say in your report that production needs a real store.
7. Check it works
Start the API first (npm run dev, npm run dev -- -p 3001 for Next.js, or uvicorn app.main:app --port 3001 --env-file .env).
curl -i http://localhost:3001/api/memust answer 401.- A POST to
/internal/v1/sign-in-checkwithout the bearer token must answer 401, and one to/internal/v1/account-createdwith the bearer token but no signature headers must answer 401. Read the token from the env in the shell, so it's never printed.
Then start the front end (npm run dev, or npm start for Angular), and ask the person to:
- Choose Sign in, then Register, and type the code OI emails. The API's log shows
[sign-in-check] … allowed, and[account-created] …, password, …. - Choose Ask the API who I am. The page shows their
sub, email, the client ID and locale. - Choose Sign out. The API's log shows
[session-ends] …, and the access token the browser had is now refused.
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. A CORS error calling the API means the front end's address isn't in FRONT_END_ORIGINS. For other errors, read https://identity-docs.otoko.com/troubleshooting.
Finish with a short report: the files you changed, the routes you added, the settings each part reads (by name), and anything the person still has to do.
More detail
- https://identity-docs.otoko.com/quickstarts/browser-app-with-api: this setup, step by step, with code for each framework.
- 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/tokens: checking tokens, making the user on its first request, and lifetimes.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
Register the app
-
In the console, open Connect an app.
-
Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes.
-
How people sign in: choose Web app, and to Does your app run server code when someone signs in? answer No: the browser swaps the code for tokens, and your API never does. Type the App address: the front end's, such as
http://localhost:5173. Open Advanced and change the Sign-in return address to the address plus/callback. Leave the Sign-out return address as the front page. -
Backend and email: type the Backend address: your API's, such as
http://localhost:3001. With OI running in Docker on your own machine, that'shttp://host.docker.internal:3001, notlocalhost. Then, for the emails:Otoko Identity emails sign-up codes, forgot-password codes and invitations. Leave Send this app's emails through Otoko Identity's mail server ticked, and the app needs no mail server of its own; a Reply-to address is optional. Only if your app has its own mail server, untick it, type the From address OI sends from, and fill in the Mail server section that appears: host, port, encryption, username and password, the last two together, and its timeouts. It's saved when the app is made, and the last step offers Send test email.
-
Choose Create. On Connect your app, use each section's own Copy all. The Frontend section's values go to the front end. The Backend section's values (
IDENTITY_URL,IDENTITY_APP_ID,IDENTITY_ALLOWED_CLIENT_IDS,IDENTITY_CALLBACK_TOKEN, and the API key) go only to the API, never the browser. The 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 API on every sign-in. Until the API is running and answers /internal/v1/sign-in-check, nobody can sign in.
Settings
The front end
Copy .env.example to .env.local, with the Frontend section's values and roles added to the scopes. VITE_API_URL is your API's address.
# Copy to .env.local. The values come from Connect an app's Frontend section (its Copy all), with VITE_ in front so
# Vite builds them into the page. None is a secret: a browser app has none. Add roles to the scopes to read roles.
VITE_IDENTITY_ISSUER=https://identity.example.com
VITE_IDENTITY_CLIENT_ID=your-client-id
VITE_IDENTITY_REDIRECT_URI=http://localhost:5173/callback
VITE_IDENTITY_SCOPES=openid profile email roles
# The API this front end calls, on another origin.
VITE_API_URL=http://localhost:3001Copy .env.example to .env.local, with the Frontend section's values and roles added to the scopes. VITE_API_URL is your API's address.
# Copy to .env.local. The values come from Connect an app's Frontend section (its Copy all), with VITE_ in front so
# Vite builds them into the page. None is a secret: a browser app has none. Add roles to the scopes to read roles.
VITE_IDENTITY_ISSUER=https://identity.example.com
VITE_IDENTITY_CLIENT_ID=your-client-id
VITE_IDENTITY_REDIRECT_URI=http://localhost:5173/callback
VITE_IDENTITY_SCOPES=openid profile email roles
# The API this front end calls, on another origin.
VITE_API_URL=http://localhost:3001Put the Frontend section's values in src/environments/environment.ts, with roles added to the scopes, and your API's address as apiUrl.
// The values from Connect an app's Frontend section (its Copy all). None is a secret: a browser app has none.
export const environment = {
identity: {
issuer: 'https://identity.example.com', // IDENTITY_ISSUER
clientId: 'your-client-id', // IDENTITY_CLIENT_ID
redirectUri: 'http://localhost:4200/callback', // IDENTITY_REDIRECT_URI
scopes: 'openid profile email roles', // IDENTITY_SCOPES, with roles added to read roles
},
apiUrl: 'http://localhost:3001', // the API this front end calls, on another origin
};The API
The IDENTITY_ values are from the Backend section's Copy all. FRONT_END_ORIGINS is your front end's address, or several separated by commas: the browser may call the API only from there. The file holds a secret, so keep it out of git.
Copy .env.example to .env.
# Copy to .env. The IDENTITY_ values come from Connect an app's Backend section (its Copy all).
# This file holds a secret: keep it out of git.
IDENTITY_URL=https://identity.example.com
IDENTITY_ALLOWED_CLIENT_IDS=your-client-id
IDENTITY_CALLBACK_TOKEN=the-webhook-secret-shown-once
# The webhook signing secret, whsec_..., made on the app's Security tab. Leave it empty until the app has one: until
# then, account.created is signed with IDENTITY_CALLBACK_TOKEN.
IDENTITY_WEBHOOK_SIGNING_SECRET=
# Your own: the front end's address, which may call this API from the browser, and this API's port.
# Vite's is http://localhost:5173, Angular's http://localhost:4200. List several with commas.
FRONT_END_ORIGINS=http://localhost:5173
PORT=3001Copy .env.example to .env.local.
# Copy to .env.local. The IDENTITY_ values come from Connect an app's Backend section (its Copy all).
# This file holds a secret: keep it out of git.
IDENTITY_URL=https://identity.example.com
IDENTITY_ALLOWED_CLIENT_IDS=your-client-id
IDENTITY_CALLBACK_TOKEN=the-webhook-secret-shown-once
# The webhook signing secret, whsec_..., made on the app's Security tab. Leave it empty until the app has one: until
# then, account.created is signed with IDENTITY_CALLBACK_TOKEN.
IDENTITY_WEBHOOK_SIGNING_SECRET=
# Your own: the front end's address, which may call this API from the browser.
# Vite's is http://localhost:5173, Angular's http://localhost:4200. List several with commas.
FRONT_END_ORIGINS=http://localhost:5173Copy .env.example to .env.
# Copy to .env. The IDENTITY_ values come from Connect an app's Backend section (its Copy all).
# This file holds a secret: keep it out of git.
IDENTITY_URL=https://identity.example.com
IDENTITY_ALLOWED_CLIENT_IDS=your-client-id
IDENTITY_CALLBACK_TOKEN=the-webhook-secret-shown-once
# The webhook signing secret, whsec_..., made on the app's Security tab. Leave it empty until the app has one: until
# then, account.created is signed with IDENTITY_CALLBACK_TOKEN.
IDENTITY_WEBHOOK_SIGNING_SECRET=
# Your own: the front end's address, which may call this API from the browser.
# Vite's is http://localhost:5173, Angular's http://localhost:4200. List several with commas.
FRONT_END_ORIGINS=http://localhost:5173Install
The front end
npm create vite@latest my-app -- --template react-ts --no-interactive
cd my-app
npm install
npm install oidc-client-ts react-router-domnpm create vite@latest my-app -- --template vue-ts --no-interactive
cd my-app
npm install
npm install oidc-client-ts vue-routernpx @angular/cli@latest new my-app --routing --style=css --ssr=false --defaults
cd my-app
npm install oidc-client-tsThe API
mkdir my-api && cd my-api
npm init -y
npm pkg set type=module scripts.dev="tsx watch --env-file=.env src/server.ts" scripts.typecheck="tsc --noEmit"npm install express jose cors
npm install -D typescript tsx @types/express @types/cors @types/nodenpx create-next-app@latest my-api --ts --app --eslint --yes --no-src-dir --import-alias "@/*"
cd my-api
npm install joseWith Python 3.10 or later. First save this as requirements.txt:
fastapi
uvicorn[standard]
pyjwt[crypto]>=2.14
httpx
python-dotenvThen:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install -r requirements.txtAdd the code
The front end
Where these files go
src/auth/oidc.ts,src/auth/useAuth.tsandsrc/auth/AuthProvider.tsx: the connection to OI, and the signed-in person for every component.src/pages/Callback.tsx: the/callbackroute.src/api.ts: calls your API with the access token.src/App.tsxandsrc/main.tsx: the routes, the front page with Ask the API who I am, and the provider around the app. These replace the starter's files.
import { UserManager } from 'oidc-client-ts';
// Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
// and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
export const userManager = new UserManager({
authority: import.meta.env.VITE_IDENTITY_ISSUER,
client_id: import.meta.env.VITE_IDENTITY_CLIENT_ID,
redirect_uri: import.meta.env.VITE_IDENTITY_REDIRECT_URI,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: import.meta.env.VITE_IDENTITY_SCOPES,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** Off to OI's sign-in page, which also has Register and Forgot password. */
export function signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
export function signOut(): Promise<void> {
return userManager.signoutRedirect();
}Where these files go
src/auth/oidc.tsandsrc/auth/useAuth.ts: the connection to OI, and the signed-in person for every component.src/views/CallbackView.vueandsrc/views/HomeView.vue: the/callbackroute, and the front page with Ask the API who I am.src/api.ts: calls your API with the access token.src/router/index.ts,src/App.vueandsrc/main.ts: the routes, and the app with its router. These replace the starter's files.
import { UserManager } from 'oidc-client-ts';
// Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
// and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
export const userManager = new UserManager({
authority: import.meta.env.VITE_IDENTITY_ISSUER,
client_id: import.meta.env.VITE_IDENTITY_CLIENT_ID,
redirect_uri: import.meta.env.VITE_IDENTITY_REDIRECT_URI,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: import.meta.env.VITE_IDENTITY_SCOPES,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** Off to OI's sign-in page, which also has Register and Forgot password. */
export function signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
export function signOut(): Promise<void> {
return userManager.signoutRedirect();
}Where these files go
src/app/auth/auth.service.ts: the connection to OI, with sign-in, sign-out and the signed-in person.src/app/api.service.ts: calls your API with the access token.src/app/callback/callback.tsandsrc/app/home/home.ts: the/callbackroute, and the front page with Ask the API who I am.src/app/app.routes.tsandsrc/app/app.html: the routes, and a page that only shows them. These replace the starter's files.
import { Injectable, signal } from '@angular/core';
import { User, UserManager } from 'oidc-client-ts';
import { environment } from '../../environments/environment';
/**
* Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
* and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly userManager = new UserManager({
authority: environment.identity.issuer,
client_id: environment.identity.clientId,
redirect_uri: environment.identity.redirectUri,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: environment.identity.scopes,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** The signed-in person, null when signed out. */
readonly user = signal<User | null>(null);
/** Whether who is signed in is known yet. */
readonly ready = signal(false);
constructor() {
this.userManager.events.addUserLoaded((loaded) => this.user.set(loaded));
this.userManager.events.addUserUnloaded(() => this.user.set(null));
this.userManager.events.addAccessTokenExpired(() => this.user.set(null));
this.userManager.getUser().then((current) => {
this.user.set(current && !current.expired ? current : null);
this.ready.set(true);
});
}
/** Off to OI's sign-in page, which also has Register and Forgot password. */
signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return this.userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
signOut(): Promise<void> {
return this.userManager.signoutRedirect();
}
/** Forgets the signed-in person in this tab only, such as when the API refuses their token. */
forget(): Promise<void> {
return this.userManager.removeUser();
}
/** On the callback page: checks the state, and swaps the code for tokens with the PKCE verifier. */
async completeSignIn(): Promise<void> {
try {
await this.userManager.signinRedirectCallback();
} catch (error) {
// A reload or Back on a used /callback ends up here: someone already signed in is fine.
if (!(await this.userManager.getUser())) {
throw error;
}
}
}
}The API: checking tokens
Your API checks every access token before trusting it, with Otoko Identity's public keys. A token passes only when:
| Check | What it means |
|---|---|
| Signature | ES256, with a key from <issuer>/. |
iss | Is Otoko Identity's address, IDENTITY_URL, exactly. |
aud and azp | Are both one of your app's client IDs, IDENTITY_ALLOWED_CLIENT_IDS. |
sub, exp, iat, jti, sid | Are all there, and exp is still in the future. |
typ | Is Bearer: an access token, not an ID token. |
service | Isn't true. A service token has nobody signed in, so an API for people refuses it. |
sid | Isn't a session Otoko Identity said had ended. |
The token names the person (sub) and the client they signed in with (azp), but not their email or roles. A front end reads those from OI's userinfo endpoint. An API that needs them looks the person up by sub in its own database, or asks userinfo with the same token.
The API: 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/token.ts:verifyAccessToken(), the token check.src/identity.tsandsrc/routes/identity.ts: the webhook secret and signature checks, the ended sessions, and OI's three routes.src/users.ts: this app's users, made byaccount.createdor on the person's first request, from OI's userinfo.src/server.ts: CORS,requireToken,GET /api/me, which makes the person's user if there's none yet, and OI's routes under/internal/v1.tsconfig.json: fornpm run typecheck.
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
import { endedSessions } from './identity.js';
const issuer = process.env.IDENTITY_URL!;
const allowedClientIds = process.env.IDENTITY_ALLOWED_CLIENT_IDS!.split(',').map((id) => id.trim());
// OI's public keys, fetched once and kept. jose fetches them again when OI signs with a new key.
const remoteKeys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
/** OI's keys couldn't be fetched, as OI or the network is down. That says nothing about the token: answer 503. */
export class KeysUnavailable extends Error {}
const keys: JWTVerifyGetKey = async (header, token) => {
try {
return await remoteKeys(header, token);
} catch (err) {
if (err instanceof errors.JWKSNoMatchingKey || err instanceof errors.JWKSMultipleMatchingKeys) {
throw err; // the token names no key of OI's: a bad token
}
throw new KeysUnavailable("OI's keys couldn't be fetched", { cause: err });
}
};
/** Checks an access token OI gave one of this app's clients, and gives back its claims. Throws for any other. */
export async function verifyAccessToken(token: string): Promise<JWTPayload> {
const { payload } = await jwtVerify(token, keys, {
issuer,
algorithms: ['ES256'],
audience: allowedClientIds, // aud must be one of this app's clients
requiredClaims: ['sub', 'exp', 'iat', 'jti', 'sid'],
});
if (!allowedClientIds.includes(payload.azp as string)) {
throw new Error("azp isn't one of this app's clients");
}
if (payload.typ !== 'Bearer') {
throw new Error('not an access token');
}
if (payload.service === true) {
throw new Error('a service token, with nobody signed in');
}
if (endedSessions.has(payload.sid as string)) {
throw new Error('the session has ended');
}
return payload;
}Where these files go
lib/token.ts:verifyAccessToken(), the token check.lib/identity.ts: the webhook secret and signature checks, and the ended sessions.lib/users.ts: this app's users, made byaccount.createdor on the person's first request, from OI's userinfo.app/api/me/route.ts:GET /api/me, with CORS for the front end. It makes the person's user if there's none yet.app/internal/v1/sign-in-check/route.ts,app/internal/v1/session-ends/route.tsandapp/internal/v1/account-created/route.ts: OI's three routes.
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
import { endedSessions } from './identity';
const issuer = process.env.IDENTITY_URL!;
const allowedClientIds = process.env.IDENTITY_ALLOWED_CLIENT_IDS!.split(',').map((id) => id.trim());
// OI's public keys, fetched once and kept. jose fetches them again when OI signs with a new key.
const remoteKeys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
/** OI's keys couldn't be fetched, as OI or the network is down. That says nothing about the token: answer 503. */
export class KeysUnavailable extends Error {}
const keys: JWTVerifyGetKey = async (header, token) => {
try {
return await remoteKeys(header, token);
} catch (err) {
if (err instanceof errors.JWKSNoMatchingKey || err instanceof errors.JWKSMultipleMatchingKeys) {
throw err; // the token names no key of OI's: a bad token
}
throw new KeysUnavailable("OI's keys couldn't be fetched", { cause: err });
}
};
/** Checks an access token OI gave one of this app's clients, and gives back its claims. Throws for any other. */
export async function verifyAccessToken(token: string): Promise<JWTPayload> {
const { payload } = await jwtVerify(token, keys, {
issuer,
algorithms: ['ES256'],
audience: allowedClientIds, // aud must be one of this app's clients
requiredClaims: ['sub', 'exp', 'iat', 'jti', 'sid'],
});
if (!allowedClientIds.includes(payload.azp as string)) {
throw new Error("azp isn't one of this app's clients");
}
if (payload.typ !== 'Bearer') {
throw new Error('not an access token');
}
if (payload.service === true) {
throw new Error('a service token, with nobody signed in');
}
if (endedSessions.has(payload.sid as string)) {
throw new Error('the session has ended');
}
return payload;
}Where these files go
app/token.py:verify_access_token(), the token check.app/identity_routes.py: the webhook secret and signature checks, the ended sessions, and OI's three routes.app/users.py: this app's users, made byaccount.createdor on the person's first request, from OI's userinfo.app/main.py: CORS,require_token, andGET /api/me, which makes the person's user if there's none yet.
"""Checks the access tokens OI gives this app's clients."""
import os
import jwt
from .identity_routes import ended_sessions
ISSUER = os.environ["IDENTITY_URL"]
ALLOWED_CLIENT_IDS = [client_id.strip() for client_id in os.environ["IDENTITY_ALLOWED_CLIENT_IDS"].split(",")]
# OI's public keys, fetched when first needed and kept. PyJWT fetches them again for a key it hasn't seen, at most
# every 30 seconds, so tokens naming made-up keys can't make this server call OI on every request.
_keys = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json", cooldown_duration=30, timeout=5)
def verify_access_token(token: str) -> dict:
"""The claims of an access token OI gave one of this app's clients. Raises jwt.PyJWTError for any other, and
jwt.PyJWKClientConnectionError when OI's keys can't be fetched."""
signing_key = _keys.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key.key,
algorithms=["ES256"],
issuer=ISSUER,
audience=ALLOWED_CLIENT_IDS, # aud must be one of this app's clients
leeway=5, # seconds, for a clock a little behind OI's
options={"require": ["sub", "exp", "iat", "jti", "sid"]},
)
if claims.get("azp") not in ALLOWED_CLIENT_IDS:
raise jwt.InvalidTokenError("azp isn't one of this app's clients")
if claims.get("typ") != "Bearer":
raise jwt.InvalidTokenError("not an access token")
if claims.get("service") is True:
raise jwt.InvalidTokenError("a service token, with nobody signed in")
if claims["sid"] in ended_sessions:
raise jwt.InvalidTokenError("the session has ended")
return claimsUsing something else?
| Part | Framework | Where |
|---|---|---|
| Front end | Svelte, Solid, plain JavaScript | The same oidc-client-ts code, with the API call in src/ (or api.js) |
| API | NestJS | A TokenGuard in src/ using jose, and an IdentityController at internal/ |
| API | Fastify | jose in a preHandler hook, @fastify/, and a plugin with OI's routes |
| API | Django REST Framework | A custom authentication class with PyJWT's PyJWKClient, django-cors-headers, and three @csrf_exempt views for OI's routes |
| API | Spring Boot | spring-boot-starter-oauth2-resource-server with the issuer's JWK set URI, plus a check of azp, typ and service |
Run and check
Start the API first, then the front end.
npm run devnpm run dev -- -p 3001uvicorn app.main:app --port 3001 --env-file .env-
Check the API refuses a call with no token. This must answer
401:curl -i http://localhost:3001/api/me -
Start the front end (
npm run dev, ornpm startfor Angular) and open it. Choose Sign in, then Register, and type the code OI emails you. The API's log shows[sign-in-check] … allowed, and[account-created] …, password, …as OI tells it of the new account. -
Choose Ask the API who I am. The page shows the API's answer: your
sub, your email, the client ID and your locale. -
Choose Sign out. The API's log shows
[session-ends] …. The access token the browser had is now refused by the API, though it hadn't expired.
Before going live
- Use https for your app and for Otoko Identity. Only
localhostmay use http. - Add your live addresses to the client, on its page in the console: the sign-in return address under Valid redirect URIs, and the front page under Valid post-logout redirect URIs. They're compared exactly, character for character.
- Build once per environment. The settings are built into the page, so each environment (staging, live) gets its own build with its own values.
- If you set a Content Security Policy, allow
connect-srcto Otoko Identity's address, as the page calls its token and userinfo endpoints. - Keep secrets out of the browser. A browser app has no client secret, and never holds an API key: anything in the page can be read.
- Keep the tokens where oidc-client-ts puts them, in sessionStorage. Never move them to localStorage.
- Serve the API over https too, and give OI its live address as the app's backend address, on the app's Overview tab.
- Set
FRONT_END_ORIGINSto your live front end's address, exactly, with no trailing slash. - Keep the webhook secret and the API key on the API only, in your host's secret settings.
- Keep ended sessions in a real store, each with the access token lifetime as its expiry, so every copy of the API 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 API's sign-in check | Start the API first. With OI in Docker, the backend address uses host.docker.internal, not localhost. |
| The browser's console shows a CORS error calling your API | The front end's address isn't in FRONT_END_ORIGINS | Add it exactly: scheme, host and port, with no trailing slash. |
The API answers 401 to a signed-in person | IDENTITY_URL isn't the issuer exactly, or the client ID isn't in IDENTITY_ALLOWED_CLIENT_IDS | Use IDENTITY_URL from the kit's Backend section, with no trailing slash, and list every client ID of the app that calls the API. |
The API's log shows 401 for /internal/ | IDENTITY_CALLBACK_TOKEN isn't the app's webhook secret | Copy it 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. |
OI answers invalid_redirect_uri | The front end's sign-in return address isn't on the client's list, exactly | Make them the same, character for character. |
| 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. |
Tested with React 19.3.1, Vite 8.3.6, react-router-dom 7.18.6 · Vue 3.5.44, vue-router 5.5.1 · Angular 22.3.0 · oidc-client-ts 3.5.0 · Express 5.3.0, jose 6.2.18, cors 2.8.6 · Next.js 16.4.6 · FastAPI 0.165.0, PyJWT 2.15.1 · Python 3.14.