Background jobs and services
In the console: a server client with Client credentials scopes, in any app
A service of yours that calls another service of yours on its own, with no person signed in: a nightly job that fetches reports, say, or one backend asking another for data. The caller proves who it is with its client ID and secret, and gets a short-lived access token from Otoko Identity (OI) with the client credentials grant. The API it calls checks the token with OI's public keys, and lets in only the services it trusts, with the scope it needs. The work itself, such as fetching the reports, is your own code on your own servers: OI only gives out the tokens, and the keys to check them.
The last part, Manage people from your server, is the other thing a server does with OI on its own: it invites someone to your app with the app's API key.
What you'll build
- The caller:
getServiceToken(), which asks OI for a token and reuses it until 30 seconds before it expires, and a script that calls the API with it, as a nightly job would. When the API answers401, it forgets the token and tries once with a new one. - The API:
GET /reports, which answers only a trusted service's token with thereports:readscope. Anything else gets401, a trusted service without the scope gets403, and503means OI's public keys couldn't be fetched to check the token. - An invite script, which emails someone an invitation to your app.
Here one server plays both the caller and the API, so you can try it on its own. In real life they're two services, and each takes only its own part of the code and the settings.
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 service's project. It tells you which client to add on the console, then writes a caller that gets service tokens, an API that checks them, and an invite with the API key.
Show the full prompt
Connect this background job or service to Otoko Identity
You are setting up a service of the person's that calls another of their services on its own, with no person signed in, through Otoko Identity (OI). The caller proves who it is with its client ID and secret, and gets a short-lived access token from OI with the OAuth client_credentials grant. The API it calls checks the token with OI's public keys, and lets in only the services it trusts, with the scope it needs. Last, the server invites someone to the app with the app's API key. Work through the steps below in order, and stop where a step says to wait for the person.
Scope
- The caller:
getServiceToken(), which asks OI for a token and reuses it until 30 seconds before it expires, and a script that calls the API with it, as a nightly job would. - The API:
GET /reports, which answers only a trusted service's token with thereports:readscope. - An invite script, which emails someone an invitation to the app.
- Ask the person whether the caller and the API are one project or two. In real life they're two services, each with only its own part of the code and the settings; the worked example runs both in one server. Use the person's own names for the route and the scope if they have them.
- Change nothing unrelated.
Rules
- The client secret and the API key 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 a front end, 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 maintained libraries: openid-client (caller) and jose (API) on Node, Authlib (caller) and PyJWT (API) in Python, or the established ones for the stack. Never write the token checks by hand.
- Use https everywhere outside a local machine.
1. Look at the project
Find the stack (Express, Next.js route handlers and FastAPI are the worked examples; Spring Boot, .NET, NestJS or Django REST Framework take the same steps), how it runs, its port (the examples use 3002), and where its routes and scripts live.
2. Tell the person what to register, then wait
The caller is a client of one of the person's apps on OI's console; you can't do this part. The API needs no client: it only checks tokens.
- 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, choose the app (or make one with Connect an app), open the Clients tab, and choose Add client:
- General settings: a Client ID, such as
reports-job, and a Name. - Capability config: turn on Client authentication, and leave the Client authenticator as it is (the secret sent as HTTP Basic). Under Client credentials scopes, choose Add scope and type
reports:read. A client with no such scope can't use the grant at all. - Login settings: leave the return addresses empty. Nobody signs in with this client.
- Choose Save. The New client secret dialog shows the secret once: paste it into the env file as
IDENTITY_CLIENT_SECRET.
- General settings: a Client ID, such as
- For the invite script, they also need the app's API key, from the Backend or Server section's Copy all when the app was made, as
IDENTITY_API_KEY. If they no longer have it, they rotate it on the app's Security tab, under API keys, and update whatever already uses it. - Ask them to tell you when it's done, and the client ID they chose (it isn't secret). Wait. Then check the env file by names only.
3. Settings
- The caller:
IDENTITY_ISSUER(OI's address),IDENTITY_CLIENT_ID,IDENTITY_CLIENT_SECRET,IDENTITY_SCOPES=reports:read, andREPORTS_API_URL, the API's address, such ashttp://localhost:3002. - The API:
IDENTITY_URL(OI's address, the tokens' issuer, with no trailing slash) andIDENTITY_TRUSTED_CALLERS, the comma-separated client IDs of the services it lets in. - The invite script:
IDENTITY_URLandIDENTITY_API_KEY. PORT=3002, and, for FastAPI with a local OI on plain http only,AUTHLIB_INSECURE_TRANSPORT=1.
Add an .env.example with the same names and placeholder values.
4. Install
- Express:
express jose openid-client, withtypescript tsx @types/express @types/nodeas dev dependencies. The examples are ES modules ("type": "module"). - Next.js:
jose openid-client. The scripts are.mtsfiles Node.js 22.18 or later runs as they are; they import../lib/service-token.tswith its extension, so add"allowImportingTsExtensions": trueundercompilerOptionsintsconfig.json. - FastAPI:
fastapi,uvicorn[standard],pyjwt[crypto],authlib,httpxandpython-dotenv.
5. The caller
getServiceToken(), such assrc/service-token.ts: OI's configuration from discovery atIDENTITY_ISSUER(<issuer>/.well-known/openid-configuration, read once, and asked again if it failed), withIDENTITY_CLIENT_IDand the secret as HTTP Basic. With openid-client, allow plain http only when the issuer ishttp:.- It asks the token endpoint with
grant_type=client_credentialsandscopeset toIDENTITY_SCOPES. The answer is an access token andexpires_in(60 seconds when absent), with no refresh token and no ID token. Log[service-token] new token, for <n> seconds, never the token. - Reuse the token until 30 seconds before it expires. Calls that come while a request to OI is on its way wait for the same token.
clearServiceToken()forgets it, so the next call asks again.- The script, such as
src/fetch-reports.ts: callsREPORTS_API_URLplus/reportswithAuthorization: Bearer <token>. On a 401, it clears the token and tries once with a new one. It reads the answer as JSON only when it is JSON, prints it, or prints the status and error and exits with 1.
6. The API
The token check, such as verifyServiceToken(token, requiredScope) in src/service-check.ts. A service token's sub, aud, azp and client_id are all the caller's client ID, scope holds its scopes separated by spaces, and "service": true says nobody signed in. It has no sid. It passes only when:
- ES256 only, with keys from
IDENTITY_URLfollowed by/.well-known/jwks.json, cached by the library, andissequal toIDENTITY_URL. audandazpboth amongIDENTITY_TRUSTED_CALLERS.sub,exp,iatandjtipresent, andexpin the future, with 5 seconds' leeway for clocks.- The
typclaim in the token's payload isBearer. With jose, check it among the claims, not with thetypoption. serviceistrue: a person's token is refused, even from a trusted client.
GET /reports, behind requireService('reports:read'):
- A missing or failing token: 401 with
WWW-Authenticate: Bearerand{"error": "invalid_token"}. - A good token without the scope: 403 with
WWW-Authenticate: Bearer error="insufficient_scope", scope="reports:read"and{"error": "insufficient_scope"}. - OI's keys couldn't be fetched at all (not a token naming an unknown key): 503
{"error": "temporarily_unavailable"}. - Otherwise:
{"caller": <sub>, "reports": [...]}.
7. The invite script
Such as src/invite.ts, taking one email as its argument. It calls POST IDENTITY_URL followed by /internal/v1/invitations with Authorization: Bearer <IDENTITY_API_KEY>, a JSON body {"email": "...", "language": "en"}, and an Idempotency-Key that is a new random UUID (a retry sends the same key again, so no second email goes). A 201 answers the invitation: print its email and expires_at. Otherwise print OI's status and error and exit with 1: 409 conflict means the email already has an account in the app. OI emails the person a link to its invitation page, where they give their name and a password.
8. Check it works
Start the server (npm run dev, npm run dev -- -p 3002 for Next.js, or uvicorn app.main:app --port 3002 --env-file .env).
curl -i http://localhost:3002/reportsmust answer 401.- In a second terminal, run the caller's script (
npx tsx --env-file=.env src/fetch-reports.ts,node --env-file=.env.local scripts/fetch-reports.mts, orpython -m app.fetch_reports). It shows[service-token] new token, and the API answers with"caller", the client ID. - Optionally, for the 403: the person adds a second client with another scope, such as
billing:read, and lists its client ID inIDENTITY_TRUSTED_CALLERStoo; its token must get 403 from/reports. Never print its secret. - The invite sends a real email. Ask the person for the address to invite, never invent one, and run the invite script with it (
npx tsx --env-file=.env src/invite.ts <email>,node --env-file=.env.local scripts/invite.mts <email>, orpython -m app.invite <email>). The email arrives with a link to OI's invitation page.
If the token request answers invalid_client, the secret is wrong or rotated, or Client authentication is off; unauthorized_client, the client has no Client credentials scopes; invalid_scope, IDENTITY_SCOPES asks for a scope not on its list. If the API answers 401 to the caller, check IDENTITY_URL is the issuer exactly and the caller is in IDENTITY_TRUSTED_CALLERS. If the invite answers 401 invalid_api_key, the API key isn't the app's current one. For other errors, read https://identity-docs.otoko.com/troubleshooting.
Finish with a short report: the files you changed, the routes and scripts 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/background-jobs-and-services: this setup, step by step, with Express, Next.js and FastAPI code.
- https://identity-docs.otoko.com/api-reference/tokens: checking tokens and lifetimes.
- https://identity-docs.otoko.com/api-reference/your-backends-calls#invitations: the invitation calls.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
Register the caller
The caller is a client of one of your apps: one you have already, or a new one made with Connect an app. The API needs no client: it only checks tokens.
- In the console, open Apps, your app, and the Clients tab. Choose Add client.
- General settings: type a Client ID, such as
reports-job, and a Name. Choose Next. - Capability config: turn on Client authentication, and leave the Client authenticator as it is (the secret sent as HTTP Basic). Under Client credentials scopes, choose Add scope and type
reports:read. Choose Next. - Login settings: leave the return addresses empty. Nobody signs in with this client.
- Choose Save. The New client secret dialog shows the secret once: copy it now.
A scope is any name you choose, in lower case, such as reports:read or billing/write, up to 20 for each client. A client with no Client credentials scopes can't use the grant at all.
For Manage people from your server, you also need the app's API key, from the Backend or Server section's Copy all when the app was made. If you no longer have it, rotate it on the app's Security tab, under API keys, and update whatever already uses it.
Settings
The client ID and the secret are the caller's. IDENTITY_TRUSTED_CALLERS lists the client IDs of the services the API lets in. The file holds the secret and the API key, so keep it out of git.
Copy .env.example to .env.
# Copy to .env. It holds secrets: keep it out of git.
# Here one server is both the caller and the API, so you can try it alone. In real life they're two services,
# and each has only its own part of this file.
# The caller: the server client you added, with Client credentials scopes.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-server-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_SCOPES=reports:read
REPORTS_API_URL=http://localhost:3002
# The API: Otoko Identity's address, and the client IDs of the services it lets in.
IDENTITY_URL=https://identity.example.com
IDENTITY_TRUSTED_CALLERS=your-server-client-id
# Managing people from your server (src/invite.ts): the app's API key, from the kit's Backend or Server section.
IDENTITY_API_KEY=the-api-key-shown-once
PORT=3002Copy .env.example to .env.local, which Next.js reads on the server only.
# Copy to .env.local, which Next.js reads on the server only. It holds secrets: keep it out of git.
# Here one server is both the caller and the API, so you can try it alone. In real life they're two services,
# and each has only its own part of this file.
# The caller: the server client you added, with Client credentials scopes.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-server-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_SCOPES=reports:read
REPORTS_API_URL=http://localhost:3002
# The API: Otoko Identity's address, and the client IDs of the services it lets in.
IDENTITY_URL=https://identity.example.com
IDENTITY_TRUSTED_CALLERS=your-server-client-id
# Managing people from your server (scripts/invite.mts): the app's API key, from the kit's Backend or Server section.
IDENTITY_API_KEY=the-api-key-shown-onceCopy .env.example to .env. With OI on plain http on your own machine, uncomment AUTHLIB_INSECURE_TRANSPORT=1, as Authlib refuses http otherwise.
# Copy to .env. It holds secrets: keep it out of git.
# Here one server is both the caller and the API, so you can try it alone. In real life they're two services,
# and each has only its own part of this file.
# The caller: the server client you added, with Client credentials scopes.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-server-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_SCOPES=reports:read
REPORTS_API_URL=http://localhost:3002
# The API: Otoko Identity's address, and the client IDs of the services it lets in.
IDENTITY_URL=https://identity.example.com
IDENTITY_TRUSTED_CALLERS=your-server-client-id
# Managing people from your server (app/invite.py): the app's API key, from the kit's Backend or Server section.
IDENTITY_API_KEY=the-api-key-shown-once
# Only with OI on plain http on your own machine, as Authlib refuses http otherwise. Never with https.
# AUTHLIB_INSECURE_TRANSPORT=1Install
A new service. For one you already have, skip the first two lines: the third sets type=module, which the examples' imports need, so check nothing of yours still uses require.
mkdir my-service && cd my-service
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 openid-client
npm install -D typescript tsx @types/express @types/nodeThe caller uses openid-client, and the API uses jose.
A new service (skip the first two lines for one you already have):
npx create-next-app@latest my-service --ts --app --eslint --yes --no-src-dir --import-alias "@/*"
cd my-service
npm install jose openid-clientThe caller uses openid-client, and the API uses jose.
A new service, with Python 3.10 or later. First save this as requirements.txt:
fastapi
uvicorn[standard]
pyjwt[crypto]
authlib
httpx
python-dotenvThen:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install -r requirements.txtThe caller uses Authlib, and the API uses PyJWT.
Add the code
The caller
The caller asks OI's token endpoint for a token with its client ID and secret, and the scope it needs. The answer is an access token and how long it lasts, with no refresh token and no ID token: when it expires, the caller simply asks again. Asking for a scope that isn't on the client's list answers invalid_scope.
getServiceToken() keeps the token, and calls that come while a request to OI is on its way wait for the same token. The script fetch-reports calls the API with it.
src/service-token.ts: the connection to OI, getServiceToken(), and clearServiceToken(). src/fetch-reports.ts: the script that calls the API.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
let cached: { accessToken: string; expiresAt: number } | undefined;
let pending: Promise<string> | undefined;
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this is your service.
*/
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;
}
async function askForToken(): Promise<string> {
const tokens = await client.clientCredentialsGrant(await getOidcConfig(), { scope: process.env.IDENTITY_SCOPES! });
const lifetime = tokens.expiresIn() ?? 60;
cached = { accessToken: tokens.access_token, expiresAt: Date.now() + lifetime * 1000 };
console.log(`[service-token] new token, for ${lifetime} seconds`);
return cached.accessToken;
}
/**
* A token for calling another service as this one, with nobody signed in: the client credentials grant. It's
* reused until 30 seconds before it expires, so most calls don't ask OI at all. There's no refresh token: a new
* one is simply asked for.
*/
export async function getServiceToken(): Promise<string> {
if (cached && Date.now() < cached.expiresAt - 30_000) {
return cached.accessToken;
}
// One request to OI at a time: calls that come while it's on its way wait for the same token.
pending ??= askForToken().finally(() => {
pending = undefined;
});
return pending;
}
/** Forgets the token, so the next call asks OI for a new one. For when the API answers 401 to it. */
export function clearServiceToken(): void {
cached = undefined;
}lib/service-token.ts: the connection to OI, getServiceToken(), and clearServiceToken(). scripts/fetch-reports.mts: the script that calls the API. Node.js 22.18 or later runs it as it is. It imports ../lib/service-token.ts with its extension, as Node.js needs, so add "allowImportingTsExtensions": true under compilerOptions in tsconfig.json.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
// On globalThis, as Next.js can load this file more than once.
const globalForToken = globalThis as unknown as {
serviceToken?: { accessToken: string; expiresAt: number };
serviceTokenPending?: Promise<string>;
};
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this is your service.
*/
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;
}
async function askForToken(): Promise<string> {
const tokens = await client.clientCredentialsGrant(await getOidcConfig(), { scope: process.env.IDENTITY_SCOPES! });
const lifetime = tokens.expiresIn() ?? 60;
globalForToken.serviceToken = { accessToken: tokens.access_token, expiresAt: Date.now() + lifetime * 1000 };
console.log(`[service-token] new token, for ${lifetime} seconds`);
return tokens.access_token;
}
/**
* A token for calling another service as this one, with nobody signed in: the client credentials grant. It's
* reused until 30 seconds before it expires, so most calls don't ask OI at all. There's no refresh token: a new
* one is simply asked for.
*/
export async function getServiceToken(): Promise<string> {
const cached = globalForToken.serviceToken;
if (cached && Date.now() < cached.expiresAt - 30_000) {
return cached.accessToken;
}
// One request to OI at a time: calls that come while it's on its way wait for the same token.
globalForToken.serviceTokenPending ??= askForToken().finally(() => {
globalForToken.serviceTokenPending = undefined;
});
return globalForToken.serviceTokenPending;
}
/** Forgets the token, so the next call asks OI for a new one. For when the API answers 401 to it. */
export function clearServiceToken(): void {
globalForToken.serviceToken = undefined;
}app/service_token.py: OI's token endpoint, from its discovery document, get_service_token(), and clear_service_token(). app/fetch_reports.py: the script that calls the API.
"""A token for calling another service as this one, with nobody signed in: the client credentials grant."""
import asyncio
import os
import time
import httpx
from authlib.integrations.httpx_client import AsyncOAuth2Client
_oauth = AsyncOAuth2Client(
client_id=os.environ["IDENTITY_CLIENT_ID"],
client_secret=os.environ["IDENTITY_CLIENT_SECRET"], # sent as HTTP Basic, the console's default
scope=os.environ["IDENTITY_SCOPES"],
)
_token_endpoint: str | None = None
_token: str | None = None
_expires_at = 0.0
_lock = asyncio.Lock()
async def _find_token_endpoint() -> str:
"""OI's token endpoint, read once from its discovery document."""
global _token_endpoint
if _token_endpoint is None:
async with httpx.AsyncClient() as http:
answer = await http.get(f"{os.environ['IDENTITY_ISSUER']}/.well-known/openid-configuration")
answer.raise_for_status()
_token_endpoint = answer.json()["token_endpoint"]
return _token_endpoint
async def get_service_token() -> str:
"""Reused until 30 seconds before it expires, so most calls don't ask OI at all. There's no refresh token: a new
one is simply asked for."""
global _token, _expires_at
# One request to OI at a time: calls that come while it's on its way wait, then reuse its token.
async with _lock:
if _token is None or time.time() > _expires_at - 30:
answer = await _oauth.fetch_token(await _find_token_endpoint(), grant_type="client_credentials")
lifetime = answer.get("expires_in") or 60 # 60 seconds when OI doesn't say
_token, _expires_at = answer["access_token"], time.time() + lifetime
print(f"[service-token] new token, for {lifetime} seconds")
return _token
def clear_service_token() -> None:
"""Forgets the token, so the next call asks OI for a new one. For when the API answers 401 to it."""
global _token
_token = NoneThe API: checking service tokens
A service token names the calling service, not a person. Its sub, aud, azp and client_id are all the caller's client ID, scope holds the scopes it was given, separated by spaces, and "service": true says nobody signed in. It has no sid. The API lets a token through 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 IDENTITY_TRUSTED_CALLERS. |
exp | Is still in the future, give or take 5 seconds for clocks a little apart. |
typ | Is Bearer: an access token. |
service | Is true. A person's token is refused, even from a client the API trusts. |
scope | Has the scope the route needs, or the answer is 403. |
Where these files go
src/service-check.ts: the token check, with jose.src/server.ts: the API'sGET /reportsbehindrequireService('reports:read').tsconfig.json: fornpm run typecheck.tsxruns the code without a build step.
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from 'jose';
const issuer = process.env.IDENTITY_URL!;
const trustedCallers = process.env.IDENTITY_TRUSTED_CALLERS!.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`));
/** A good token whose scopes don't include the one the route needs: answer 403, not 401. */
export class MissingScopeError extends Error {}
/** OI's public keys couldn't be fetched, so the token couldn't be checked at all: answer 503, not 401. */
export class KeysUnavailableError extends Error {}
/** The key the token names. Failing to fetch the key set is OI's trouble, not the token's. */
async function keys(...args: Parameters<typeof remoteKeys>) {
try {
return await remoteKeys(...args);
} catch (error) {
if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys) {
throw error; // the token names a key OI doesn't have
}
throw new KeysUnavailableError("OI's key set couldn't be fetched", { cause: error });
}
}
/**
* Checks a token another service got with the client credentials grant, and gives back its claims. Throws
* MissingScopeError without the scope, KeysUnavailableError when OI's keys can't be fetched, and an error for any
* other token. There's no sid to check: nobody signed in.
*/
export async function verifyServiceToken(token: string, requiredScope: string): Promise<JWTPayload> {
const { payload } = await jwtVerify(token, keys, {
issuer,
algorithms: ['ES256'],
audience: trustedCallers, // aud is the calling service's own client ID
requiredClaims: ['sub', 'exp', 'iat', 'jti'],
clockTolerance: 5, // seconds, for clocks a little apart
});
if (!trustedCallers.includes(payload.azp as string)) {
throw new Error("azp isn't a caller this API trusts");
}
if (payload.typ !== 'Bearer') {
throw new Error('not an access token');
}
if (payload.service !== true) {
throw new Error("a person's token: this API is for services");
}
const scopes = typeof payload.scope === 'string' ? payload.scope.split(' ') : [];
if (!scopes.includes(requiredScope)) {
throw new MissingScopeError(`the token hasn't ${requiredScope}`);
}
return payload;
}Where these files go
lib/service-check.ts: the token check, with jose.app/reports/route.ts: the API'sGET /reports.
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload } from 'jose';
const issuer = process.env.IDENTITY_URL!;
const trustedCallers = process.env.IDENTITY_TRUSTED_CALLERS!.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`));
/** A good token whose scopes don't include the one the route needs: answer 403, not 401. */
export class MissingScopeError extends Error {}
/** OI's public keys couldn't be fetched, so the token couldn't be checked at all: answer 503, not 401. */
export class KeysUnavailableError extends Error {}
/** The key the token names. Failing to fetch the key set is OI's trouble, not the token's. */
async function keys(...args: Parameters<typeof remoteKeys>) {
try {
return await remoteKeys(...args);
} catch (error) {
if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys) {
throw error; // the token names a key OI doesn't have
}
throw new KeysUnavailableError("OI's key set couldn't be fetched", { cause: error });
}
}
/**
* Checks a token another service got with the client credentials grant, and gives back its claims. Throws
* MissingScopeError without the scope, KeysUnavailableError when OI's keys can't be fetched, and an error for any
* other token. There's no sid to check: nobody signed in.
*/
export async function verifyServiceToken(token: string, requiredScope: string): Promise<JWTPayload> {
const { payload } = await jwtVerify(token, keys, {
issuer,
algorithms: ['ES256'],
audience: trustedCallers, // aud is the calling service's own client ID
requiredClaims: ['sub', 'exp', 'iat', 'jti'],
clockTolerance: 5, // seconds, for clocks a little apart
});
if (!trustedCallers.includes(payload.azp as string)) {
throw new Error("azp isn't a caller this API trusts");
}
if (payload.typ !== 'Bearer') {
throw new Error('not an access token');
}
if (payload.service !== true) {
throw new Error("a person's token: this API is for services");
}
const scopes = typeof payload.scope === 'string' ? payload.scope.split(' ') : [];
if (!scopes.includes(requiredScope)) {
throw new MissingScopeError(`the token hasn't ${requiredScope}`);
}
return payload;
}Where these files go
app/service_check.py: the token check, with PyJWT.app/main.py: the API'sGET /reportsbehindrequire_service("reports:read").
"""Checks the tokens other services get with the client credentials grant."""
import os
import time
import jwt
ISSUER = os.environ["IDENTITY_URL"]
TRUSTED_CALLERS = [client_id.strip() for client_id in os.environ["IDENTITY_TRUSTED_CALLERS"].split(",")]
# OI's public keys, fetched when first needed and kept for 5 minutes.
_keys = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json")
_last_refetch = 0.0
class MissingScopeError(Exception):
"""A good token whose scopes don't include the one the route needs: answer 403, not 401."""
def _find_key(kid: str | None, refresh: bool) -> jwt.PyJWK | None:
return next((key for key in _keys.get_signing_keys(refresh=refresh) if key.key_id == kid), None)
def _signing_key(token: str) -> jwt.PyJWK:
"""The key the token names. For a key it hasn't seen, as when OI signs with a new one, it fetches the keys again,
but at most every 30 seconds: tokens with made-up kids can't make it ask OI on every request. Raises
jwt.PyJWKClientConnectionError when the keys can't be fetched."""
global _last_refetch
kid = jwt.get_unverified_header(token).get("kid")
key = _find_key(kid, refresh=False)
if key is None and time.monotonic() - _last_refetch > 30:
_last_refetch = time.monotonic()
key = _find_key(kid, refresh=True)
if key is None:
raise jwt.InvalidTokenError("no key for this kid")
return key
def verify_service_token(token: str, required_scope: str) -> dict:
"""The claims of a trusted service's token. Raises MissingScopeError without the scope, and jwt.PyJWTError for
any other token. There's no sid to check: nobody signed in."""
claims = jwt.decode(
token,
_signing_key(token).key,
algorithms=["ES256"],
issuer=ISSUER,
audience=TRUSTED_CALLERS, # aud is the calling service's own client ID
leeway=5, # seconds, for clocks a little apart
options={"require": ["sub", "exp", "iat", "jti"]},
)
if claims.get("azp") not in TRUSTED_CALLERS:
raise jwt.InvalidTokenError("azp isn't a caller this API trusts")
if claims.get("typ") != "Bearer":
raise jwt.InvalidTokenError("not an access token")
if claims.get("service") is not True:
raise jwt.InvalidTokenError("a person's token: this API is for services")
if required_scope not in str(claims.get("scope", "")).split():
raise MissingScopeError(f"the token hasn't {required_scope}")
return claimsManage people from your server
Your server can also invite people to your app, with the app's API key. OI emails them a link to its invitation page, where they give their name and a password. Their account is made only then, with the email already verified. Inviting the same email again replaces the open invitation, and an email that already has an account answers 409 conflict.
src/invite.ts: a script that invites one email.
// Invites someone to your app by email, from your server, with the app's API key:
// npx tsx --env-file=.env src/invite.ts [email protected]
// OI emails them a link to its invitation page, where they give their name and a password. Their account is made
// only then, with the email already verified.
import { randomUUID } from 'node:crypto';
const email = process.argv[2];
if (!email) {
throw new Error('Usage: npx tsx --env-file=.env src/invite.ts [email protected]');
}
const res = await fetch(`${process.env.IDENTITY_URL}/internal/v1/invitations`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.IDENTITY_API_KEY}`,
'Content-Type': 'application/json',
// A random key for this invitation. It matters once you retry: send the same key again, and OI sends no second email.
'Idempotency-Key': randomUUID(),
},
body: JSON.stringify({ email, language: 'en' }),
});
// Read the answer only when it's JSON: a proxy in front of OI may answer with an HTML error page.
const answer = res.headers.get('content-type')?.includes('json') ? await res.json() : {};
if (res.status === 201) {
console.log(`Invited ${answer.email}. The link works until ${answer.expires_at}.`);
} else {
// 409 conflict: this email already has an account in the app.
console.error(`OI answered ${res.status} ${answer.error ?? res.statusText}`);
process.exitCode = 1;
}scripts/invite.mts: a script that invites one email. Node.js 22.18 or later runs it as it is.
// Invites someone to your app by email, from your server, with the app's API key:
// node --env-file=.env.local scripts/invite.mts [email protected]
// Node.js 22.18 or later runs TypeScript as it is.
// OI emails them a link to its invitation page, where they give their name and a password. Their account is made
// only then, with the email already verified.
import { randomUUID } from 'node:crypto';
const email = process.argv[2];
if (!email) {
throw new Error('Usage: node --env-file=.env.local scripts/invite.mts [email protected]');
}
const res = await fetch(`${process.env.IDENTITY_URL}/internal/v1/invitations`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.IDENTITY_API_KEY}`,
'Content-Type': 'application/json',
// A random key for this invitation. It matters once you retry: send the same key again, and OI sends no second email.
'Idempotency-Key': randomUUID(),
},
body: JSON.stringify({ email, language: 'en' }),
});
// Read the answer only when it's JSON: a proxy in front of OI may answer with an HTML error page.
const answer = res.headers.get('content-type')?.includes('json') ? await res.json() : {};
if (res.status === 201) {
console.log(`Invited ${answer.email}. The link works until ${answer.expires_at}.`);
} else {
// 409 conflict: this email already has an account in the app.
console.error(`OI answered ${res.status} ${answer.error ?? res.statusText}`);
process.exitCode = 1;
}app/invite.py: a script that invites one email.
"""Invites someone to your app by email, from your server, with the app's API key:
python -m app.invite [email protected]
OI emails them a link to its invitation page, where they give their name and a password. Their account is made only
then, with the email already verified."""
import os
import sys
import uuid
import httpx
from dotenv import load_dotenv
def main() -> None:
load_dotenv() # reads .env
if len(sys.argv) != 2:
sys.exit("Usage: python -m app.invite [email protected]")
answer = httpx.post(
f"{os.environ['IDENTITY_URL']}/internal/v1/invitations",
headers={
"Authorization": f"Bearer {os.environ['IDENTITY_API_KEY']}",
# A random key for this invitation. It matters once you retry: send the same key again, and OI sends no
# second email.
"Idempotency-Key": str(uuid.uuid4()),
},
json={"email": sys.argv[1], "language": "en"},
)
# Read the answer only when it's JSON: a proxy in front of OI may answer with an HTML error page.
body = answer.json() if "json" in answer.headers.get("content-type", "") else {}
if answer.status_code == 201:
print(f"Invited {body['email']}. The link works until {body['expires_at']}.")
else:
# 409 conflict: this email already has an account in the app.
sys.exit(f"OI answered {answer.status_code} {body.get('error', answer.reason_phrase)}")
if __name__ == "__main__":
main()Using something else?
| Part | Framework | How |
|---|---|---|
| Caller | Any HTTP client | POST <issuer>/ with grant_type=client_credentials and scope=… as a form, and the client ID and secret as HTTP Basic |
| Caller | Spring Boot | spring-boot-starter-oauth2-client with authorization-grant-type: client_credentials, and a WebClient or RestClient that adds the token |
| Caller | .NET | Duende.AccessTokenManagement, which keeps the token until it expires |
| API | NestJS | A ServiceTokenGuard using jose, with the scope from a @RequiresScope('reports:read') decorator |
| API | Spring Boot | spring-boot-starter-oauth2-resource-server with the issuer's JWK set URI, plus a check of aud, azp, service and scope |
| API | Django REST Framework | A custom authentication class with PyJWT's PyJWKClient, and a permission class for the scope |
Run and check
npm run devnpm run dev -- -p 3002uvicorn app.main:app --port 3002 --env-file .env-
Check the API refuses a call with no token. This must answer
401:curl -i http://localhost:3002/reports -
Try a token without the scope. Add a second client as in step 1, with another scope such as
billing:read, and put its client ID inIDENTITY_TRUSTED_CALLERStoo. Get its token, and call the API with it. This must answer403:curl -s -u "billing-job:its-secret" -d grant_type=client_credentials https://identity.example.com/oauth/token curl -i http://localhost:3002/reports -H "Authorization: Bearer <the access_token>"
In a second terminal, run the caller's script. It gets a token from OI, shows [service-token] new token, and calls the API, which answers with "caller", your client ID. Each run is a new process, so each asks OI for a new token; a service that keeps running reuses its token until 30 seconds before it expires.
npx tsx --env-file=.env src/fetch-reports.tsnode --env-file=.env.local scripts/fetch-reports.mtspython -m app.fetch_reportsThen invite someone. The email arrives with a link to OI's invitation page.
npx tsx --env-file=.env src/invite.ts [email protected]node --env-file=.env.local scripts/invite.mts [email protected]python -m app.invite [email protected]Before going live
- Use https for OI and for the API, so neither the secret nor the token crosses the network in the clear.
- Keep the client secret and the API key in your host's secret settings, never in git or in a front end. 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.
- Give each service its own client, with only the scopes it needs, so the API can tell them apart and you can cut one off without the others.
- Keep the token check's list short:
IDENTITY_TRUSTED_CALLERSnames only the services that may call this API. - Send the same
Idempotency-Keywhen you retry an invitation, so a retry after a timeout sends no second email.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
The token request answers 401 invalid_client | The client secret is wrong or rotated, or Client authentication is off | Copy the current secret from the client's Credentials tab, and check Client authentication is on. |
The token request answers unauthorized_client | The client has no Client credentials scopes, or isn't confidential | Add a scope under Client credentials scopes, with Client authentication on. |
The token request answers invalid_scope | IDENTITY_SCOPES asks for a scope that isn't on the client's list | Ask only for scopes on its list, or add the scope to the client. |
The API answers 401 to the caller | IDENTITY_URL isn't the issuer exactly, or the caller's client ID isn't in IDENTITY_TRUSTED_CALLERS | Use the issuer with no trailing slash, and list the caller's client ID. |
The API answers 503 | The API couldn't fetch OI's public keys from IDENTITY_URL | Check the API can reach <IDENTITY_URL>/, then try again. |
The API answers 403 | The token hasn't the route's scope | Add the scope to the caller's Client credentials scopes, and ask for it in IDENTITY_SCOPES. |
FastAPI says InsecureTransportError | OI is on plain http | On your own machine, set AUTHLIB_INSECURE_TRANSPORT=1. Use https anywhere else. |
The invite answers 401 invalid_api_key | IDENTITY_API_KEY isn't the app's current API key | Rotate it on the app's Security tab, and use the new one. |
The invite answers 409 conflict | This email already has an account in the app | Nothing to do: they can sign in, or use Forgot password. |
The invite answers 503 mail_server_not_set_up | The app sends email through a mail server that isn't set up | On the app's Email tab, send through OI's mail server, or finish setting up your own. |
Tested with Express 5.3.0, tsx 4.23.15 · Next.js 16.4.6 · openid-client 6.9.0, jose 6.2.18 · FastAPI 0.165.0, Authlib 1.9.9, httpx 0.28.1, PyJWT 2.15.1, Python 3.14 · Node.js 24.