Skip to Content
Otoko Identity

Calls to your backend

The routes Otoko Identity calls on your backend, what each receives and answers, and how to check the signed ones.

What Otoko Identity calls on your backend. A backend is optional: an app with none gets no calls. Its settings are on the Overview.

Agent prompt

Paste this into your coding agent, in your backend's project. It adds the routes Otoko Identity calls, the sign-in check, account created and ended sessions, checks Otoko Identity's tokens in your APIs, and makes your user on its first request.

Show the full prompt

Add Otoko Identity's backend routes and token checks to this backend

You are working in the backend of an app that signs people in with Otoko Identity (OI). Add the routes OI calls on the backend, and check OI's access tokens in the backend's own APIs. Work through the steps below in order, and stop where a step says to wait for the person.

Scope

Rules

  • The webhook secret and the API key live only in the backend'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 a log line or a commit.
  • For the token checks, use a maintained JWT library, such as jose for Node or PyJWT for Python. Never write them by hand.
  • Use https everywhere outside a local machine.

1. Look at the backend and its settings

  • Find the backend's stack, how it runs, its port, where its routes live, and any sign-in middleware or CSRF protection it has.
  • Check by name only that its env file holds IDENTITY_URL, IDENTITY_APP_ID, IDENTITY_CALLBACK_TOKEN and IDENTITY_ALLOWED_CLIENT_IDS, the settings in the Backend section of the console's kit.
  • If they aren't there, the app isn't registered yet. Tell the person to:
    1. register it at https://identity.otoko.com/admin/apps/new, answering Yes to Does your app have an API that Otoko Identity calls?, with the Backend address where OI reaches this backend (with OI in Docker on the same machine, http://host.docker.internal:<port>, not localhost);
    2. paste the Backend section's Copy all into this env file, which you've checked git ignores;
    3. tell you when it's done.

    Then wait.

2. The sign-in check route (required)

OI asks the backend on every sign-in, mobile sign-ins included, whether this person may use the app, and anything other than {"allowed": true} keeps them out. Until this route works, nobody can sign in. Add it exactly so:

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 }
  • Compare the bearer token with IDENTITY_CALLBACK_TOKEN in constant time, and answer 401 to anything else.
  • Refuse ({"allowed": false}) a client_id that isn't in IDENTITY_ALLOWED_CLIENT_IDS, a comma-separated list.
  • Answer {"allowed": true} for everyone else for now. Leave a comment that a real app checks its own records here, such as a blocked account, an unpaid plan or a missing invitation.
  • pending_actions names the app's own required actions still pending for this person, the screens an app may make people pass before signing in. A new app sets none, so leave it be unless the person asks.
  • Keep it read-only and fast: OI waits 3 seconds. Answer from the backend's own records, and make no user here. Step 6 makes them.

3. The ended sessions route

OI tells the backend which sessions ended, so it can refuse their access tokens at once, not when they expire:

POST /internal/v1/session-ends
Authorization: Bearer <IDENTITY_CALLBACK_TOKEN>
Content-Type: application/json

{ "sids": ["..."], "sub": "..." or null, "ended_at": "2026-11-17T10:00:00Z" }
  • Check the bearer token as above.
  • Store each sid, up to 500 per call. sub is the person when all of them are one person's, and null for a sign-out of everyone.
  • Answer any 2xx once they're stored, and 503 when the store is down: anything else, or no answer, is tried again for 6 hours from ended_at. A second call with the same sids changes nothing.
  • Refuse those sessions' access tokens, with the same 401 as an expired one, for as long as one could still pass your check: its longest lifetime from ended_at.

4. The account created route

OI tells the backend of a new account, once per person, signed with the Standard Webhooks headers alongside the bearer token:

POST /internal/v1/account-created
Authorization: Bearer <IDENTITY_CALLBACK_TOKEN>
Content-Type: application/json
webhook-id: 0f8e2a61-0000-4000-8000-000000000000
webhook-timestamp: 1763546400
webhook-signature: v1,<base64 signature>

{ "type": "account.created", "data": { "sub": "...", "email": "...", "email_verified": true, "first_name": "...", "last_name": "...", "language": "en", "client_id": "...", "method": "password", "created_at": "2026-11-19T10:00:00Z" } }
  • Check the bearer token as above.
  • Verify the signature, on the raw body bytes before any JSON parsing: base64 of HMAC-SHA256 over webhook-id, a dot, webhook-timestamp, a dot, then the body, keyed with IDENTITY_WEBHOOK_SIGNING_SECRET, the app's whsec_ signing secret from its Security tab, whose key is the base64-decoded bytes after whsec_. Until the app has one, the key is IDENTITY_CALLBACK_TOKEN's own UTF-8 bytes, not base64-decoded: read the key from whichever is set, the signing secret first, and tell the person to make a signing secret if there is none. During a rotation the previous secret signs too, for 7 days. webhook-signature may hold several v1, entries separated by spaces: refuse more than 10, and accept any that matches, compared in constant time.
  • Answer 401 to a missing or bad signature, or a webhook-timestamp that isn't unix seconds or is more than 5 minutes from the backend's clock. Parse it so a value such as ² is refused, not an error and a 500.
  • Record each webhook-id, and answer 2xx at once, doing nothing more, when it's already there: a retry or a replay sends it again.
  • Upsert the user keyed by sub, the same upsert as step 6. Names may be null.
  • Answer 2xx as soon as it's stored, within 5 seconds, and 503 when the store is down: a 4xx is never tried again.
  • If the backend keeps no users of its own, skip this step and step 6, and say so in your report.

5. Check OI's tokens in the backend's APIs

Every route that needs a signed-in person checks the bearer access token, and answers 401 to a missing or failing one:

  • ES256 only, with keys from IDENTITY_URL followed by /.well-known/jwks.json (cache them, and fetch again for a key ID you don't have), and iss equal to IDENTITY_URL.
  • aud and azp both among IDENTITY_ALLOWED_CLIENT_IDS.
  • The typ claim in the token's payload is Bearer. It's a claim, not the JWT header's typ: with jose, check it among the claims, not with the typ option.
  • iss, sub, exp, iat, jti and sid all present, and sid not among the ended sessions.
  • Refuse a token with "service": true in routes that serve people.

6. Make the backend's user on its first request

This is where the backend makes its users. The account created route only makes them earlier, and it may be late or lost.

  • In the code that resolves the signed-in person, after the token passes step 5, look the user up by sub.
  • If there is none, call IDENTITY_URL followed by /oauth/userinfo with the same access token as Authorization: Bearer. It answers email and email_verified with the email scope, and given_name, family_name and locale with profile. Allow for missing names.
  • Upsert keyed by sub: a unique key on sub, an insert that ignores a conflict, then read the row, so two first requests at once make one user. Never key users on the email.

7. Keep OI's calls out of the sign-in middleware

OI calls the /internal/v1/ routes server to server, with the bearer token and no cookies. Exempt them from the backend's sign-in middleware and CSRF protection, or every sign-in fails.

8. Check it works

  • Call the sign-in check route the way OI does, reading the token from the env in the shell so it's never printed, such as curl -X POST -H "Authorization: Bearer $IDENTITY_CALLBACK_TOKEN" .... Expect {"allowed": true}, and 401 with a wrong token.
  • Call the account created route the same way with no signature headers, and expect 401.
  • Then sign in through the app, and call one protected route with the access token.

Finish with a short report: the files you changed, the routes you added, the settings the code reads (by name), and anything the person still has to do.

More detail

Routes Otoko Identity calls

Each call is a POST with the webhook secret as a bearer token in the Authorization header. The account-created call is signed as well.

RouteIt receivesIt answersNotes
/internal/v1/sign-in-check{sub, client_id, pending_actions}{"allowed": true|false}Required with a backend. Asked on every sign-in, after a password and after an identity provider. Read-only, and waited for 3 seconds. Any other answer fails sign-in closed, and no answer or a 5xx follows If the backend can't be reached.
/internal/v1/account-created{type, data}, signedAny 2xx once it's storedOptional. Tells the backend of a new account. Tried again for about 31 hours, then kept for a replay. See When someone signs up.
/internal/v1/sign-up-check{email, client_id, method}{"allowed": true}, or {"allowed": false, "reason": "..."}Only with the app's Ask the backend before sign-up on. Asked before a sign-up, by password or provider. Any other answer, or none, stops the sign-up with 503.
/internal/v1/sso-accounts{email, first_name, last_name, language, client_id, provider_type}201 {"identity_id": "..."}, or a 4xx with {"error": {"reason": "..."}}Only for an app whose account flows are its backend's, with a provider that may make accounts. The names are null when the provider gave none.
/internal/v1/session-ends{"sids": [...], "sub": "..." or null, "ended_at": "..."}Any 2xx once they're stored. Anything else is tried again for 6 hours.Optional. Tells the backend which sessions ended, so it refuses their access tokens at once.
/internal/v1/email-results{dispatch_id, recipient, sent}Optional. A failure is logged and goes no further.Optional. Tells the backend how an email it asked for with a dispatch_id ended: a code, a set-password link or an invitation.

A sign-in check, the request and the answer:

POST /internal/v1/sign-in-check
Authorization: Bearer <the webhook secret>
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 }

The sign-in check

  • It's a yes or no, read-only: answer from your backend's own records, such as a blocked account or a suspended organization, and make nothing here. Your backend makes its user on its first request.
  • One try, waited for 3 seconds.
  • A circuit breaker per app: after 5 calls in a row with no answer or a 5xx within 60 seconds, Otoko Identity stops calling your backend for 60 seconds and applies the outage policy below at once. Then one call goes through to see if it's back.

If the backend can't be reached

Under Login on the app's Overview tab, If the backend can't be reached says what a sign-in, and a sign-up asked about with Ask the backend before sign-up, does when the check gets no answer in 3 seconds, a 5xx, or finds the breaker open. A wrong answer, or {"allowed": false}, always refuses.

  • Refuse sign-in, the default, and what every app had before: the sign-in fails, and a sign-up answers 503.
  • Allow sign-in, opt-in, and only for an app with a backend, or saving answers 422 backend_required:
    • the person signs in, and the app's Events tab records sign_in_check.skipped, with the reason backend_unreachable or circuit_open;
    • at that session's next refresh, Otoko Identity asks the sign-in check again. Yes clears the mark. No ends the session, as a revoke does, and the refresh answers invalid_grant. No answer applies the policy again;
    • a sign-up goes on too, recorded as sign_up_check.skipped, and its account.created event says "sign_up_check": "skipped", so your backend can apply its sign-up rules when the event arrives.

Warning

Choose Allow sign-in only if your backend enforces its own rules on every request, such as a blocked account or a removed member, from its own database. Otherwise, while your backend is down, the sign-in check can't say no, and the access token given stays good until it expires.

Accounts made through an identity provider

  • Only for an app whose account flows are its backend's, with a provider that may make accounts. Otherwise Otoko Identity makes the account itself, verified, after the sign-up check if it's on, and sends account.created. Make the account as your sign-up does, its identity through POST /internal/v1/identities with your API key, verified and enabled, as the provider vouched for the address, and answer 201 with its identity_id. An identity that isn't verified or can't sign in is refused.
  • Answer 403, 404, 409 or 422 to refuse: the sign-in then fails with nothing made or linked. An app whose backend has no such route makes no accounts this way. A 5xx or no answer reads as an outage.
  • To have the person told why, on a 4xx, put one of these reasons in the body as {"error": {"reason": "..."}}. Any other reason, or none, shows the generic error page.
ReasonMeans
personal_emailA free mail address.
domain_takenA domain an organization already holds.
account_existsAn address with an account.
sign_up_not_offeredThis client doesn't sign people up this way.

Hearing of ended sessions

  • Up to 500 sids a call, each the sid of that session's access tokens. sub is the person when they are all one person's, and null for a sign-out of everyone.
  • Refuse their access tokens from then on, with the same 401 as an expired one, for as long as one could still pass your check: its longest lifetime from ended_at.
  • Answer 2xx once they are stored. Anything else, or no answer, is tried again for 6 hours from ended_at, so answer 503 when your store is down, and make a second call with the same sids change nothing.
  • A backend without the route still works: a sign-out then takes effect when the token expires.

Asking before a sign-up

  • Only with Ask the backend before sign-up on, under Login on the app's Overview tab. It is off by default, and needs a backend.
  • method is password, or the type of the identity provider signing the person up. It is asked before the email is looked up.
  • Answer {"allowed": true} to go on, or {"allowed": false} to refuse, with a reason from the table above to have the page say why.
  • Any other answer stops the sign-up with 503. No answer, a 5xx or an open breaker does too, unless the app's outage policy is Allow sign-in: then the sign-up goes on, recorded as skipped.

When someone signs up

Otoko Identity tells your backend of a new account with an account.created event, at POST /internal/v1/account-created. It's a notice: no sign-in waits for it, and if it's late or lost your backend still makes the user on its first request. A backend without the route answers 404, and the event goes no further.

It's sent at most once per app and person, only for an app with a backend:

  • when a sign-up's address is first verified: by its emailed code, by a sign-in code, or by a set-password link;
  • at sign-up, for an app with Verify email for new accounts off;
  • after a first sign-in through Google, Microsoft or an OpenID Connect provider, where Otoko Identity makes the account, as it does unless the account flows are your backend's;
  • when someone accepts an invitation.

Never for an account your backend made itself through POST /internal/v1/identities, your sso-accounts route's included, as your backend knows of those already.

POST /internal/v1/account-created
Authorization: Bearer <the webhook secret>
Content-Type: application/json
webhook-id: 0f8e2a61-0000-4000-8000-000000000000
webhook-timestamp: 1763546400
webhook-signature: v1,<the signature>

{
  "type": "account.created",
  "data": {
    "sub": "5b1c6f0e-0000-4000-8000-000000000000",
    "email": "[email protected]",
    "email_verified": true,
    "first_name": "Ada",
    "last_name": "Lovelace",
    "language": "en",
    "client_id": "your-client-id",
    "method": "password",
    "phone_number": "+4915112345678",
    "birthdate": "1990-05-01",
    "sign_up_check": "passed",
    "created_at": "2026-11-19T10:00:00.123456+00:00"
  }
}
  • method is password, google, microsoft, oidc or invitation, and client_id is the client the person signed up through. It's null for an accepted invitation, and for a sign-up verified by a set-password link: handle both.
  • The names are null when an identity provider gave none.
  • phone_number, in E.164, and birthdate, as YYYY-MM-DD, are null unless the app's sign-up asks for them and the person gave them. See Sign-up fields.
  • sign_up_check is passed, skipped (let through by the outage policy) or not_asked (no backend, the check off, an invitation). Your receiver should ignore fields it doesn't know, as more may be added.

Verify its signature

The headers are Standard Webhooks':

HeaderWhat it holds
webhook-idThe delivery's id, the same on every retry and replay.
webhook-timestampWhen it was sent, in unix seconds.
webhook-signaturev1, and the signature, in base64. Several are separated by spaces.
  • The signature is an HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{body}.
  • The key is the app's webhook signing secret. Make one under Webhook signing secret on the app's Security tab. It's shown once, as whsec_ and base64, and the key is the base64-decoded bytes after whsec_: the form a Standard Webhooks library takes as it is. Give it to your backend as IDENTITY_WEBHOOK_SIGNING_SECRET.
  • Until the app has one, it's signed with the webhook secret instead, IDENTITY_CALLBACK_TOKEN, keyed with its own UTF-8 bytes, not base64-decoded. That secret is also the bearer token on every call, so anyone who sees one call's headers could sign another: make a signing secret, and check with it.
  • Rotating it keeps the previous one signing beside the new one for 7 days, as a second v1, signature, so your backend can move to the new one first. Retire now stops the previous one within about a minute, for one that leaked.
  • From the moment the app's first signing secret is made, OI signs with it alone. Until your backend has it, deliveries go dead with 401: once it does, Replay them from the app's Webhook deliveries. Make it before the app has people, as the Quickstarts do, and there's nothing to replay.
  • The body is the raw bytes received, before any JSON parsing. Parsed and serialized again, it won't match.
  • Answer 401 to a timestamp more than 5 minutes from your clock, to more than 10 signatures, or to no matching signature. Compare in constant time. A 401 makes the delivery dead at once, as a wrong secret won't get better by waiting.
  • The bearer header comes too, for now: check it as on the other routes.

Both samples take either secret: a whsec_ signing secret, or the webhook secret until the app has one. To test yours, the secret webhook-secret-for-tests, webhook-id msg_2KWPBgLlAfxdpx2AI54pPJ85f4W, webhook-timestamp 1674087231 and the body {"type":"account.created","data":{"sub":"x"}} sign as v1,n0hQ3YZl4zyNuBzT5ABgcTQEzajU/z98oy4lmrKQrys=, with a clock that allows that timestamp.

In Python, with headers whose names are looked up case-insensitively, such as Starlette's request.headers:

import base64
import hashlib
import hmac
import time
from collections.abc import Mapping

WEBHOOK_ID_HEADER = "webhook-id"
WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp"
WEBHOOK_SIGNATURE_HEADER = "webhook-signature"
SIGNATURE_VERSION = "v1"
SIGNING_SECRET_PREFIX = "whsec_"
TOLERANCE_SECONDS = 5 * 60
# One signature per secret in use, so a rotation sends two.
MAX_SIGNATURES = 10


def read_key(secret: str) -> bytes:
    """A whsec_ signing secret's key is the base64 after the prefix; the webhook secret's, its own UTF-8 bytes."""
    if secret.startswith(SIGNING_SECRET_PREFIX):
        return base64.b64decode(secret.removeprefix(SIGNING_SECRET_PREFIX))

    return secret.encode()


def is_signature_valid(secret: str, headers: Mapping[str, str], body: bytes) -> bool:
    """Whether a delivery was signed with `secret`, the app's whsec_ signing secret or, until it has one, its webhook
    secret, within TOLERANCE_SECONDS of this clock.

    `headers` must look names up case-insensitively, and `body` is the raw bytes received. False, for a 401, when a
    header is missing, the timestamp is malformed or stale, there are more than MAX_SIGNATURES, or none matches.
    """
    webhook_id = headers.get(WEBHOOK_ID_HEADER)
    timestamp = headers.get(WEBHOOK_TIMESTAMP_HEADER)
    signature_header = headers.get(WEBHOOK_SIGNATURE_HEADER)
    if webhook_id is None or timestamp is None or signature_header is None:
        return False

    # int() refuses what isn't a number, such as "²", which isdigit() lets through.
    try:
        sent_at = int(timestamp)
    except ValueError:
        return False

    if abs(time.time() - sent_at) > TOLERANCE_SECONDS:
        return False

    entries = signature_header.split(" ")
    if len(entries) > MAX_SIGNATURES:
        return False

    signed_content = f"{webhook_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(read_key(secret), signed_content, hashlib.sha256).digest())
    signatures = (entry.partition(",") for entry in entries)

    return any(
        version == SIGNATURE_VERSION and hmac.compare_digest(given.encode(), expected)
        for version, _, given in signatures
    )

In TypeScript, on Node, with Express's req.headers and the body kept raw, such as with express.raw({ type: "application/json" }) on this route:

import { createHmac, timingSafeEqual } from "node:crypto";
import type { IncomingHttpHeaders } from "node:http";

const WEBHOOK_ID_HEADER = "webhook-id";
const WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
const WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
const SIGNATURE_VERSION = "v1";
const SIGNING_SECRET_PREFIX = "whsec_";
const TOLERANCE_SECONDS = 5 * 60;
const MILLISECONDS_PER_SECOND = 1000;
// One signature per secret in use, so a rotation sends two.
const MAX_SIGNATURES = 10;
const UNIX_SECONDS_PATTERN = /^[0-9]+$/;

// A header sent once. Node hands over an array only for a header it doesn't join, which none of these is.
function readHeader(headers: IncomingHttpHeaders, name: string): string | undefined {
  const value = headers[name];

  return typeof value === "string" ? value : undefined;
}

// A whsec_ signing secret's key is the base64 after the prefix; the webhook secret's, its own UTF-8 bytes.
function readKey(secret: string): Buffer {
  return secret.startsWith(SIGNING_SECRET_PREFIX)
    ? Buffer.from(secret.slice(SIGNING_SECRET_PREFIX.length), "base64")
    : Buffer.from(secret, "utf8");
}

/**
 * Whether a delivery was signed with `secret`, the app's whsec_ signing secret or, until it has one, its webhook
 * secret, within TOLERANCE_SECONDS of this clock. `headers` are Node's, as
 * Express's `req.headers`, and `body` is the raw bytes received. False, for a 401, when a header is missing, the
 * timestamp is malformed or stale, there are more than MAX_SIGNATURES, or none matches.
 */
export function isSignatureValid(secret: string, headers: IncomingHttpHeaders, body: Buffer): boolean {
  const id = readHeader(headers, WEBHOOK_ID_HEADER);
  const timestamp = readHeader(headers, WEBHOOK_TIMESTAMP_HEADER);
  const signatureHeader = readHeader(headers, WEBHOOK_SIGNATURE_HEADER);
  if (id === undefined || timestamp === undefined || signatureHeader === undefined) {
    return false;
  }

  const nowSeconds = Date.now() / MILLISECONDS_PER_SECOND;
  if (!UNIX_SECONDS_PATTERN.test(timestamp) || Math.abs(nowSeconds - Number(timestamp)) > TOLERANCE_SECONDS) {
    return false;
  }

  const entries = signatureHeader.split(" ");
  if (entries.length > MAX_SIGNATURES) {
    return false;
  }

  const expected = createHmac("sha256", readKey(secret)).update(`${id}.${timestamp}.`).update(body).digest();

  return entries.some((entry) => {
    const [version, signature = ""] = entry.split(",");
    const given = Buffer.from(signature, "base64");

    return version === SIGNATURE_VERSION && given.length === expected.length && timingSafeEqual(given, expected);
  });
}

Store it once, and answer fast

  • Delivery is at least once, so the same event can come again. Record each webhook-id, in the same transaction as the user, or after it, never before: a failure between the two would otherwise lose the user. Answer 2xx at once, doing nothing more, when it's already there.
  • Upsert the user keyed by sub, the same upsert as on the first request, so the two can come in either order.
  • Leave what the person must still choose, such as an organization, to a required action.
  • Answer any 2xx as soon as it's stored, within 5 seconds, and do slow work, such as a welcome email, after answering.

Retries, dead deliveries and replays

  • A 5xx, no answer in 5 seconds, or no connection is tried again after 30 seconds, 2 minutes, 10 minutes, 1 hour, 6 hours and 24 hours. Then the delivery is dead.
  • A 4xx is dead at once, as your backend refused it on purpose. So answer 503, not a 4xx, when your store is down.
  • The app's Webhook deliveries in the console lists dead deliveries with their last error. Replay sends one again, with the same webhook-id, and the replay is audited. Dead deliveries are kept for 30 days.