Skip to content
Select theme

OAuth protocol walkthrough

AI agent getting started? Read Agents: start here first.

Use this guide to debug a connection or implement a client in a language without the SDK helper. First register your client and keep its private key on your backend.

Set the API origin and the values from registration:

Terminal window
export API="https://api.example.com" # the API origin, https, no trailing slash
export CLIENT_ID="<client identifier from registration>"
export REDIRECT_URI="https://app.example.com/callback" # exactly as registered

The authorization server is mounted at /oauth on the API origin and publishes its metadata there:

Terminal window
curl -s "$API/oauth/.well-known/openid-configuration"

The answer lists authorization_endpoint, token_endpoint, jwks_uri and revocation_endpoint. It lists S256 as the only code-challenge method and private_key_jwt and none as the client authentication methods. It offers no registration, introspection, device or user-info endpoint: clients register through the Administration module, not through the protocol.

PKCE is required and only S256 is accepted. Generate a verifier, a challenge and a state value, and keep the verifier and state on your backend:

Terminal window
export VERIFIER=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')
export CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')
export STATE=$(openssl rand -hex 16)
echo "$API/oauth/auth?client_id=$CLIENT_ID&redirect_uri=$REDIRECT_URI&response_type=code&scope=objects.read%20offline_access&code_challenge=$CHALLENGE&code_challenge_method=S256&state=$STATE&prompt=consent"
  1. If the authorization_endpoint from step 1 differs from the path shown, use that endpoint.
  2. Open the printed address in a browser, sign in and approve the access. The scope parameter lists the requested scopes; the user may approve fewer.
  3. Include prompt=consent with offline_access. Without it, the server drops that scope and issues no refresh token.

Redirect addresses must match exactly. An authorization code lasts 60 seconds and works once.

  1. When the browser reaches your redirect address, read its code and state parameters.
  2. If nothing is listening there, copy the full address from the browser’s address bar.
  3. Check that state equals the value you sent. Reject the callback if it does not.

A confidential client proves itself with a signed assertion (private_key_jwt, ES256, signed with the private key whose public key set you registered). The assertion’s iss and sub are the client identifier, its aud is the issuer ($API/oauth), and it lives for at most five minutes. A public client sends no assertion and no secret.

This request carries the assertion, so a script builds it. Save the following as redeem.mjs and run it with the values above in the environment (Node.js 22 or later, with npm install oauth4webapi run beside it):

import * as oauth from "oauth4webapi";
import { readFileSync } from "node:fs";
const issuer = new URL("/oauth", process.env.API);
const server = await oauth.processDiscoveryResponse(
issuer,
await oauth.discoveryRequest(issuer, { algorithm: "oidc" }),
);
const client = { client_id: process.env.CLIENT_ID };
const pem = readFileSync(process.env.PRIVATE_KEY_FILE, "utf8");
const key = await crypto.subtle.importKey(
"pkcs8",
Buffer.from(pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, ""), "base64"),
{ name: "ECDSA", namedCurve: "P-256" },
false,
["sign"],
);
const callback = new URL(process.env.CALLBACK_URL);
const parameters = oauth.validateAuthResponse(server, client, callback, process.env.STATE);
const response = await oauth.authorizationCodeGrantRequest(
server,
client,
oauth.PrivateKeyJwt(key),
parameters,
process.env.REDIRECT_URI,
process.env.VERIFIER,
);
const tokens = await oauth.processAuthorizationCodeResponse(server, client, response);
console.log(JSON.stringify(tokens));
Terminal window
export PRIVATE_KEY_FILE="./client-private-key.pem" # keys.privateKey, saved when you generated it
export CALLBACK_URL="<the full address copied from the browser>"
node redeem.mjs

The answer holds access_token, token_type (bearer, as sent by the server), scope, expires_in (900 seconds) and, when offline_access was approved, refresh_token. The access token is an opaque string of 43 URL-safe characters. A refresh token works once: refreshing returns a new one, and reusing an old one revokes the grant. Refresh with grant_type=refresh_token at the same token endpoint, authenticating with a fresh assertion.

4. Know which organisation the token names

Section titled “4. Know which organisation the token names”

The access token is attached to the organisation where the client was registered.

The Clients page lists the client identifier but does not show an organisationId. The person must belong to that organisation to approve the connection, and the token carries no authority in any other organisation. The host reads the organisation from the verified token and never from a request. A client may still send the organisation it expects, as a precondition, in the oe2-expected-organisation header. The host compares it with the token’s organisation before the route runs and refuses a difference with session-moved (the organisation in the request differs from the token); it never uses the sent value.

Every route answers one JSON envelope. The routes that carry data take POST with a JSON body; the health check and the two sign-in navigation routes take GET. These headers matter:

HeaderValueMeaning
content-typeapplication/jsonThe body is JSON.
oe2-protocol-version50Required by routes that refuse a missing or different value.
authorizationBearer <access token>The only evidence of the caller the host reads.
oe2-expected-organisationan organisation identifier (optional)The precondition from step 4.
oe2-idempotency-keyone to 128 characters of letters, digits, ., _, ~, -Required on a route whose help shows idempotent: yes. Reuse one key only to repeat the same mutation.
oe2-step-up-keyone to 128 characters of letters, digits, ., _, ~, -On a non-idempotent call held for confirmation, carries the key for that call. An idempotent route uses its oe2-idempotency-key as the key.
Terminal window
export ACCESS_TOKEN="<access_token from step 3>"
export PROJECT_ID="<project identifier>"
export OBJECT_ID="<object identifier>"
curl -s -X POST "$API/objects/read" \
-H "content-type: application/json" \
-H "oe2-protocol-version: 50" \
-H "authorization: Bearer $ACCESS_TOKEN" \
-d "{\"selector\":{\"projectId\":\"$PROJECT_ID\",\"ref\":\"main\"},\"input\":{\"objectId\":\"$OBJECT_ID\"}}"

A route acting on a project, branch or ref takes a selector beside its input. It names the target project and branch or baseline. A route without a selector, such as registerClient, takes only input. The answer is an envelope. Its version matches the host protocol version. A success carries the route result:

{
"version":50,
"result": {
"objectId":"...",
"projectId":"...",
"typeKey":"requirement",
"typeVersionId":"...",
"lock":"none",
"properties":{
"title":{
"value":"The first requirement",
"modifiedAt":"...",
"modifiedBy":"..."
}
},
"createdAt":"...",
"createdBy":"...",
"modifiedAt":"...",
"modifiedBy":"..."
}
}

A refusal is a structured error response. It carries the refusal details and the request’s correlationId, never a result:

{
"version":50,
"refusal":{"kind":"session-moved","organisationId":"..."},
"correlationId":"..."
}

Test the precondition by sending a different organisation:

Terminal window
curl -s -i -X POST "$API/objects/read" \
-H "content-type: application/json" \
-H "oe2-protocol-version: 50" \
-H "oe2-expected-organisation: org_not_yours" \
-H "authorization: Bearer $ACCESS_TOKEN" \
-d "{\"selector\":{\"projectId\":\"$PROJECT_ID\",\"ref\":\"main\"},\"input\":{\"objectId\":\"$OBJECT_ID\"}}"

The status is 409 and the refusal kind is session-moved. Transport refusals map as follows: protocol-mismatch and invalid-request are 400; unauthenticated is 401; not-attached is 403 when no organisation is selected for the CLI session; not-found is 404; and in-flight is 409 when another operation is still running. bound-exceeded means a request or operation limit was exceeded.

It is 413 for oversized bodies, 400 for query limits and 429 for other count limits or request-duration: a write request that ran past its time limit before its write started; nothing was written. A route-level rejection is refused (403) with a rule reason code. unknown-outcome (504) means completion could not be determined; inspect or recover before retrying. Branch on the refusal kind, not status alone. The SDK modules build these requests.