Guides

OIDC client integration

Wire an application to ulex as an OpenID Connect client: discovery, dynamic client setup, PKCE, the authorization code flow, token storage, JWKS verification, logout, and how to test it without a browser.

This guide is written for the engineer or agent building your application, with ulex as the identity provider.

#1. Discovery

Point your OIDC library at the discovery document. Do not hardcode endpoints.

ts
import { Issuer } from "openid-client";

const issuer = await Issuer.discover("https://ulexid.com");
const client = new issuer.Client({
  client_id: "client_01M3PSV7J8TBSPHG95CYSEX32B",
  client_secret: process.env.ULEX_CLIENT_SECRET!,     // cs_…  from GET /applications/{id}/secret
  redirect_uris: ["https://app.example.com/auth/callback"],
  response_types: ["code"],
  token_endpoint_auth_method: "client_secret_post",
});

console.log(issuer.metadata.scopes_supported);
console.log(issuer.metadata.claims_supported);
console.log(issuer.metadata.code_challenge_methods_supported); // ["S256","plain"] — use S256

Use separate OIDC clients for hosted (https://ulexid.com) and local in-memory testing (http://127.0.0.1:3001 via npx @ulexid/mcp-server):

SurfaceIssuerClient id
Hosted control planehttps://ulexid.comclient_01M3PSV7J8TBSPHG95CYSEX32B
Local in-memory serverhttp://127.0.0.1:3001minted on startup

Never reuse a local client configuration against hosted https://ulexid.com. Tokens carry the issuer that minted them (iss), and a mismatch fails validation at your resource server.

#2. Redirect URIs

bash
curl -sS -X POST "$BASE/applications" \
  -H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: 1f4c9e2a-3b7d-4a1e-9c58-0f2a6b3d81cc" \
  -d '{
    "name": "Acme Support",
    "slug": "acme-support",
    "redirect_uris": [
      "https://app.example.com/auth/callback",
      "https://staging.app.example.com/auth/callback",
      "http://localhost:3000/auth/callback"
    ],
    "grant_types": ["authorization_code", "refresh_token"],
    "response_types": ["code"],
    "response_mode": "form_post",
    "require_pkce": true,
    "pkce_methods": ["S256"]
  }'
  • http:// is accepted only for localhost, 127.0.0.1, ::1. Anything else is 400 validation_failed.
  • https:// redirects must be exact: no wildcards, no query strings, no fragments, and a trailing slash is a different URI.
  • 50 redirect URIs maximum.
  • response_mode: "form_post" means the callback arrives as a POST, not a GET. Set your framework up for both and prefer form_post; it keeps the code out of browser history and server logs.

#3. PKCE, always

require_pkce is true by default and pkce_methods is ["S256"]. There is no configuration in which you should turn it off.

ts
import { randomBytes, createHash } from "node:crypto";

function pkce(): { verifier: string; challenge: string } {
  const verifier = randomBytes(32).toString("base64url");
  const challenge = createHash("sha256").update(verifier).digest("base64url");
  return { verifier, challenge };
}

RFC 7636 Appendix B test vector, which the simulator honours verbatim for mock_sso connections:

text
code_verifier  = dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
code_challenge = E9MelhoQ2YvW96fl8sW7aTtZbGd0mY6Xl0e8Q1sCk

ulex_simulate_login uses that vector by default so an agent never has to get base64url-SHA256 right on the first attempt. Pass return_pkce: true to get a generated pair instead.

#4. Authorize

http
GET https://ulexid.com/api/v1/oauth2/authorize
  ?response_type=code
  &client_id=client_01M3PSV7J8TBSPHG95CYSEX32B
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fauth%2Fcallback
  &scope=openid%20profile%20email%20offline_access
  &state=st_9Kq2WmB7yLt4NxZ
  &nonce=nc_3Fq8Lp2XvN9bTm
  &code_challenge=E9MelhoQ2YvW96fl8sW7aTtZbGd0mY6Xl0e8Q1sCk
  &code_challenge_method=S256

Generate and store state and nonce in the user's session before redirecting. Reject the callback if either does not match. state is CSRF protection; nonce binds the id_token to this authorization.

Parameters that matter beyond the required set:

ParameterUse
organizationorg id or slug; pre-selects the customer. Puts the org in the token's org_id claim.
connection_idforce a specific connection. Must be active.
login_hintpre-fills the email on the hosted screen
promptlogin forces re-auth; none fails with login_required if there is no session, and with consent_required if there is a session but no approval for the scopes asked for; select_account; consent re-asks even when you already approved
max_age=3600re-authenticate if the session is older than an hour
acr_valuesdemand a higher assurance level, e.g. urn:ulex:acr:mfa
ui_localesBCP-47 list, e.g. en-GB fr
claimsJSON requesting extra claims, e.g. {"id_token":{"org_role":null}}

Response, form_post:

html
<form method="post" action="https://app.example.com/auth/callback">
  <input type="hidden" name="code" value="ac_8Kq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8">
  <input type="hidden" name="state" value="st_9Kq2WmB7yLt4NxZ">
  <input type="hidden" name="iss" value="https://ulexid.com">
</form>

The iss parameter is the mix-up defence. Check it — the callback is only valid if iss equals your expected issuer.

Errors come back as a redirect to your callback with error and error_description, but only when redirect_uri and state both validate. Otherwise you get a rendered error page.

html
<code>access_denied</code>
The organization only allows SSO through con_01M3PSVAG0QFJG99R0M5DXSR5A.
json
{
  "error": "login_required",
  "error_description": "prompt=none was requested but there is no active session.",
  "type": "authentication_error",
  "code": "login_required",
  "request_id": "req_01M3PSW9R0175NAW62NYR403R8",
  "retryable": false
}

Codes you must handle: access_denied, login_required, interaction_required, consent_required, account_selection_required, mfa_required, step_up_required, invalid_scope, invalid_request_uri, unauthorized_client.

#5. Token

bash
curl -sS -X POST "https://ulexid.com/api/v1/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=authorization_code&
      code=ac_8Kq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8&
      redirect_uri=https://app.example.com/auth/callback&
      client_id=client_01M3PSV7J8TBSPHG95CYSEX32B&
      client_secret=cs_9fKq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8&
      code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleV8wMU0zUFNWSkEwWVAyV0RQTTJSRFIxNU1HSCIsInR5cCI6IkpXVCJ9…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "rt_51KpXq8WvN0kTzRb7YcLd2mXe9Pf6Sg3AuV8",
  "refresh_token_expires_in": 2592000,
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleV8wMU0zUFNWSkEwWVAyV0RQTTJSRFIxNU1HSCIsInR5cCI6IkpXVCJ9…",
  "scope": "openid profile email offline_access"
}

The code lives 60 seconds. Exchange immediately, do not queue it.

#6. Store tokens correctly

ts
interface StoredToken {
  access_token: string;
  refresh_token: string;
  id_token: string;
  expires_at: number;        // epoch seconds
  scope: string;
}

export async function persistRotation(previous: StoredToken, next: StoredToken): Promise<void> {
  // A rotating refresh token means the old one is dead the moment you use it.
  // Write the new pair in ONE atomic operation, before the new access token
  // is used anywhere. A two-step write is a data race that ends in
  // invalid_grant and a family revocation.
  await db.transaction(async (tx) => {
    await tx.run(
      "UPDATE sessions SET access_token = ?, refresh_token = ?, expires_at = ?, scope = ? WHERE id = ?",
      [next.access_token, next.refresh_token, next.expires_at, next.scope, previous.session_id],
    );
  });
}

Rotate on a timer, not on request. A proactive refresh at expires_at - 300 avoids a user-visible 401 entirely.

ts
export function needsRefresh(stored: StoredToken, skewSeconds = 300, now = Date.now() / 1000): boolean {
  return stored.expires_at - skewSeconds <= now;
}

#7. Verify the access token

ts
import { createLocalJWKSet, jwtVerify, decodeProtectedHeader } from "jose";

const jwks = createLocalJWKSet(
  await (await fetch("https://ulexid.com/api/v1/oauth2/keys")).json(),
);

export async function verifyAccessToken(token: string) {
  const { payload, protectedHeader } = await jwtVerify(token, jwks, {
    issuer: "https://ulexid.com",
    audience: "client_01M3PSV7J8TBSPHG95CYSEX32B",
    algorithms: ["RS256"],
    clockTolerance: 30,
  });
  return { claims: payload, kid: protectedHeader.kid };
}
Warning

Never decode a token and trust it. Decoding is not verifying. A JWT's payload is signed over, not encrypted: anyone can read it and anyone can forge it if you skip signature verification.

Always check, in this order:

  1. signature against the JWKS, keyed by kid
  2. iss equals your expected issuer exactly
  3. aud contains your client_id (or azp equals it)
  4. exp is in the future, with 30 s of clock tolerance
  5. nbf if present
  6. azp when aud has more than one entry

#8. Cache the JWKS properly

This is the single most common integration bug.

ts
const jwksCache = new Map<string, { key: crypto.KeyObject; expiresAt: number }>();
const JWKS_TTL_MS = 15 * 60_000;

async function refreshJwks(): Promise<void> {
  const res = await fetch("https://ulexid.com/api/v1/oauth2/keys", {
    headers: { Authorization: `Bearer ${process.env.ULEX_API_KEY!}` },
  });
  const { keys } = (await res.json()) as { keys: Array<Record<string, unknown> & { kid: string }> };
  jwksCache.clear();
  for (const jwk of keys) {
    jwksCache.set(jwk.kid, { key: await crypto.subtle.importKey(...), expiresAt: Date.now() + JWKS_TTL_MS });
  }
}
Anti-patternConsequence
Pinning one kidbreaks the first time a signing key rotates
Caching foreveraccepts tokens signed by a revoked key
Refetching on every verification3,000 requests a minute
Refetching only on unknown kid, never on a TTLa revoked key stays trusted
Empty map on fetch failure, then "not found"a transient blip logs out every user

Correct shape: a kid-keyed map, 15-minute TTL, a single-flight refresh, and the old entries survive a refresh so in-flight tokens keep verifying during a rotation.

#9. Logout

http
GET https://ulexid.com/api/v1/auth/session/end
  ?id_token_hint=<id_token>
  &post_logout_redirect_uri=https%3A%2F%2Fapp.example.com%2Fbye
  &state=st_9Kq2WmB7yLt4NxZ

post_logout_redirect_uri must be in the application's cross_app_sso_redirect_urls. Logout terminates the session and revokes the refresh-token family.

#10. Testing it without a browser

ts
describe("OIDC login", () => {
  it("issues a valid access token bound to the right organization", async () => {
    const grant = await tools.ulex_simulate_login({
      application_id: "app_01M3PSV7J8TBSPHG95CYSEX32B",
      organization_id: "org_01M3PSV8HGTKQFCAYF9GDWGN3C",
      email: "dana@acme.example",
    });
    expect(grant.outcome).toBe("success");

    const tokens = await tools.ulex_exchange_code_for_tokens({
      application_id: "app_01M3PSV7J8TBSPHG95CYSEX32B",
      code: grant.code,
      redirect_uri: "https://app.example.com/auth/callback",
      code_verifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
    });

    const { claims } = await verifyAccessToken(tokens.access_token);
    expect(claims.sub).toBe("usr_01M3PSV9GRT8GQGEG686AR1W9S");
    expect(claims.org_id).toBe("org_01M3PSV8HGTKQFCAYF9GDWGN3C");
  });
});

Full suite, including the error paths: Testing an SSO flow headlessly.

#Reference