Skip to Content
Otoko Identity

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 answers 401, it forgets the token and tries once with a new one.
  • The API: GET /reports, which answers only a trusted service's token with the reports:read scope. Anything else gets 401, a trusted service without the scope gets 403, and 503 means 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.

Agent prompt

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 the reports:read scope.
  • 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.
  • 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.

  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, 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.
  3. 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.
  4. 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, and REPORTS_API_URL, the API's address, such as http://localhost:3002.
  • The API: IDENTITY_URL (OI's address, the tokens' issuer, with no trailing slash) and IDENTITY_TRUSTED_CALLERS, the comma-separated client IDs of the services it lets in.
  • The invite script: IDENTITY_URL and IDENTITY_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, with typescript tsx @types/express @types/node as dev dependencies. The examples are ES modules ("type": "module").
  • Next.js: jose openid-client. The scripts are .mts files Node.js 22.18 or later runs as they are; they import ../lib/service-token.ts with its extension, so add "allowImportingTsExtensions": true under compilerOptions in tsconfig.json.
  • FastAPI: fastapi, uvicorn[standard], pyjwt[crypto], authlib, httpx and python-dotenv.

5. The caller

  • getServiceToken(), such as src/service-token.ts: OI's configuration from discovery at IDENTITY_ISSUER (<issuer>/.well-known/openid-configuration, read once, and asked again if it failed), with IDENTITY_CLIENT_ID and the secret as HTTP Basic. With openid-client, allow plain http only when the issuer is http:.
  • It asks the token endpoint with grant_type=client_credentials and scope set to IDENTITY_SCOPES. The answer is an access token and expires_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: calls REPORTS_API_URL plus /reports with Authorization: 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_URL followed by /.well-known/jwks.json, cached by the library, and iss equal to IDENTITY_URL.
  • aud and azp both among IDENTITY_TRUSTED_CALLERS.
  • sub, exp, iat and jti present, and exp in the future, with 5 seconds' leeway for clocks.
  • The typ claim in the token's payload is Bearer. With jose, check it among the claims, not with the typ option.
  • service is true: 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: Bearer and {"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).

  1. curl -i http://localhost:3002/reports must answer 401.
  2. 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, or python -m app.fetch_reports). It shows [service-token] new token, and the API answers with "caller", the client ID.
  3. Optionally, for the 403: the person adds a second client with another scope, such as billing:read, and lists its client ID in IDENTITY_TRUSTED_CALLERS too; its token must get 403 from /reports. Never print its secret.
  4. 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>, or python -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

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.

  1. In the console, open Apps, your app, and the Clients tab. Choose Add client.
  2. General settings: type a Client ID, such as reports-job, and a Name. Choose Next.
  3. 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.
  4. Login settings: leave the return addresses empty. Nobody signs in with this client.
  5. 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.

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

Install

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

The caller uses openid-client, and the API uses jose.

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;
}

The 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:

CheckWhat it means
SignatureES256, with a key from <issuer>/.well-known/jwks.json.
issIs Otoko Identity's address, IDENTITY_URL, exactly.
aud and azpAre both one of IDENTITY_TRUSTED_CALLERS.
expIs still in the future, give or take 5 seconds for clocks a little apart.
typIs Bearer: an access token.
serviceIs true. A person's token is refused, even from a client the API trusts.
scopeHas the scope the route needs, or the answer is 403.

Where these files go

service-check.ts
server.ts
tsconfig.json
  • src/service-check.ts: the token check, with jose.
  • src/server.ts: the API's GET /reports behind requireService('reports:read').
  • tsconfig.json: for npm run typecheck. tsx runs 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;
}

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

src/invite.ts
// 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;
}

Using something else?

PartFrameworkHow
CallerAny HTTP clientPOST <issuer>/oauth/token with grant_type=client_credentials and scope=… as a form, and the client ID and secret as HTTP Basic
CallerSpring Bootspring-boot-starter-oauth2-client with authorization-grant-type: client_credentials, and a WebClient or RestClient that adds the token
Caller.NETDuende.AccessTokenManagement, which keeps the token until it expires
APINestJSA ServiceTokenGuard using jose, with the scope from a @RequiresScope('reports:read') decorator
APISpring Bootspring-boot-starter-oauth2-resource-server with the issuer's JWK set URI, plus a check of aud, azp, service and scope
APIDjango REST FrameworkA custom authentication class with PyJWT's PyJWKClient, and a permission class for the scope

Run and check

npm run dev
  1. Check the API refuses a call with no token. This must answer 401:

    curl -i http://localhost:3002/reports
  2. 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 in IDENTITY_TRUSTED_CALLERS too. Get its token, and call the API with it. This must answer 403:

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

Then invite someone. The email arrives with a link to OI's invitation page.

npx tsx --env-file=.env src/invite.ts [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_CALLERS names only the services that may call this API.
  • Send the same Idempotency-Key when you retry an invitation, so a retry after a timeout sends no second email.

If something goes wrong

What you seeWhyWhat to do
The token request answers 401 invalid_clientThe client secret is wrong or rotated, or Client authentication is offCopy the current secret from the client's Credentials tab, and check Client authentication is on.
The token request answers unauthorized_clientThe client has no Client credentials scopes, or isn't confidentialAdd a scope under Client credentials scopes, with Client authentication on.
The token request answers invalid_scopeIDENTITY_SCOPES asks for a scope that isn't on the client's listAsk only for scopes on its list, or add the scope to the client.
The API answers 401 to the callerIDENTITY_URL isn't the issuer exactly, or the caller's client ID isn't in IDENTITY_TRUSTED_CALLERSUse the issuer with no trailing slash, and list the caller's client ID.
The API answers 503The API couldn't fetch OI's public keys from IDENTITY_URLCheck the API can reach <IDENTITY_URL>/.well-known/jwks.json, then try again.
The API answers 403The token hasn't the route's scopeAdd the scope to the caller's Client credentials scopes, and ask for it in IDENTITY_SCOPES.
FastAPI says InsecureTransportErrorOI is on plain httpOn your own machine, set AUTHLIB_INSECURE_TRANSPORT=1. Use https anywhere else.
The invite answers 401 invalid_api_keyIDENTITY_API_KEY isn't the app's current API keyRotate it on the app's Security tab, and use the new one.
The invite answers 409 conflictThis email already has an account in the appNothing to do: they can sign in, or use Forgot password.
The invite answers 503 mail_server_not_set_upThe app sends email through a mail server that isn't set upOn 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.