API

Authentication

How to authenticate to ulex: API keys, user access tokens, OAuth 2.1 client credentials, the full scope list, request headers, token lifetimes, MCP authentication including RFC 9728 protected-resource metadata, and how to mint and revoke keys.

Every ulex surface — REST, MCP, CLI, and SCIM — uses one of four credential types. They are not interchangeable; using the wrong one is the single most common cause of a 401.

CredentialSent asAuthorisesMinted by
API keyAuthorization: Bearer ulex_sk_live_…the whole control planePOST /tenants/current/api-keys
Access tokenAuthorization: Bearer eyJ…one application, one userPOST /oauth2/token
SCIM tokenAuthorization: Bearer scim_…inbound /scim/v2 onlyGET /directories/{id}/scim (once)
Webhook secretUlex-Signature headerverifies inbound deliveries to your endpointPOST /webhooks (once)
Warning

An API key can call GET /oauth2/userinfo and get a 403 insufficient_scope, because an API key is not a user. And an access token can call POST /applications and get a 403 for the same reason. Pick the credential that matches the operation.

#Base URL

text
https://ulexid.com/api/v1

For local in-memory testing with npx @ulexid/mcp-server, the local server listens at http://127.0.0.1:3001/api/v1.

Discovery endpoints live at the origin (and under /api/v1 for OAuth/protected-resource metadata):

text
https://ulexid.com/.well-known/openid-configuration
https://ulexid.com/api/v1/.well-known/oauth-authorization-server
https://ulexid.com/api/v1/.well-known/oauth-protected-resource

#API keys

#Mint

bash
BASE="https://ulexid.com/api/v1"

curl -sS -X POST "$BASE/tenants/current/api-keys" \
  -H "Authorization: Bearer $ULEX_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 7c1f2a90-4d3b-4e8a-9f21-0c5b6d7e8a91" \
  -d '{
    "name": "agent-bootstrap",
    "scope": ["mcp:tools", "read:organizations", "write:organizations", "read:users", "write:users"],
    "expires_in_days": 90,
    "application_id": null,
    "ip_allowlist": []
  }'
json
{
  "api_key": {
    "id": "key_01M3PSVJA0YP2WDPM2RDR15MGH",
    "object": "api_key",
    "name": "agent-bootstrap",
    "prefix": "ulex_sk_live_7Qm2K",
    "scope": ["mcp:tools", "read:organizations", "write:organizations", "read:users", "write:users"],
    "application_id": null,
    "ip_allowlist": [],
    "last_used_at": null,
    "expires_at": "2026-12-28T09:00:00.000Z",
    "revoked_at": null,
    "expires_in_days": 90,
    "created_at": "2026-09-29T09:00:00.000Z"
  },
  "key": "ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au",
  "warning": "This is the only time the key is returned. Store it now."
}

#Format and prefixes

text
ulex_sk_live_<32 chars>    hosted tenant key
ulex_sk_test_<32 chars>    test / local key
ulex_sk_<32 chars>         accepted key format

The prefix field stores the first 14 characters in cleartext for lookup; the remainder is stored as a scrypt hash with a per-tenant salt. The full key is never persisted, never logged, and never returned again — not by GET /tenants/current/api-keys, not by GET /applications/{id}/secret, not by any MCP tool.

#Use

bash
curl -sS "$BASE/me" -H "Authorization: Bearer ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au"
json
{
  "id": "key_01M3PSVJA0YP2WDPM2RDR15MGH",
  "object": "api_key",
  "tenant_id": "ten_01M3PSV6K0HFZ62YZ6AKB191WW",
  "name": "agent-bootstrap",
  "prefix": "ulex_sk_live_7Qm2K",
  "scope": ["mcp:tools", "read:organizations", "write:organizations", "read:users", "write:users"],
  "application_id": null,
  "ip_allowlist": [],
  "last_used_at": "2026-09-29T14:42:03.000Z",
  "last_used_ip_hash": "sha256:9c2e4a6b8d0f2a4c6e8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c2e4b6d8f0a2c",
  "expires_at": "2026-12-28T09:00:00.000Z",
  "revoked_at": null,
  "created_at": "2026-09-29T09:00:00.000Z"
}

#List, revoke, rotate

bash
curl -sS "$BASE/tenants/current/api-keys" -H "Authorization: Bearer $ULEX_ADMIN_KEY" | jq '.data[] | {id, name, prefix, last_used_at, expires_at, revoked_at}'

curl -sS -X DELETE "$BASE/tenants/current/api-keys/key_01M3PSVJA0YP2WDPM2RDR15MGH" \
  -H "Authorization: Bearer $ULEX_ADMIN_KEY"
json
{
  "id": "key_01M3PSW9R0175NAW62NYR403R8",
  "object": "api_key",
  "revoked_at": "2026-09-29T15:02:11.000Z",
  "revoked": true
}

Revocation is immediate and total. A revoked key returns 401 api_key_revoked on its very next call — there is no grace period, because a leaked key must be dead on the next request.

#Best practice

ts
// Do this.
const key = process.env.ULEX_API_KEY;
if (!key) throw new Error("ULEX_API_KEY is not set");

// Not this.
const key = "ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au";

Minimum viable key hygiene:

  1. One key per workload. Never share a key between a CI job and a local agent.
  2. expires_in_days of 90 or less, always. A key with no expiry is a key you will forget.
  3. ip_allowlist with CIDRs when the caller has a fixed egress.
  4. Scope narrowly. mcp:tools + the four read:* scopes covers most agent work.
  5. ulex:admin only in CI, and only from a protected runner.
  6. Rotate on any suspicion of exposure. There is no cost to rotation; mint a new key, deploy, revoke the old one.

#Scopes

ScopeGrants
openidsub claim and the OIDC discovery handshake
profilename, nickname, picture claims
emailemail and email_verified claims
offline_accessa refresh token
ulex:admineverything, including key rotation, signing-key rotation, and impersonation
read:organizationsGET /organizations*, /domains, /members
write:organizationsPOST/PATCH/PUT/DELETE on the same
read:usersGET /users*
write:usersPOST/PATCH/DELETE /users*, suspend/unsuspend
read:groupsGET /groups*
write:groupsgroup and membership writes
read:connectionsGET /connections*, /saml/metadata, /saml/login
write:connectionsconnection CRUD, /activate, /verify
read:directoriesGET /directories*
write:directoriesdirectory CRUD, /sync
read:applicationsGET /applications*, /secret, /metadata
write:applicationsapplication CRUD, /rotate-secret
read:webhooksGET /webhooks*, /deliveries
write:webhookswebhook CRUD, /enable, /disable, /test
read:audit_logsGET /audit-events*
read:deploymentsGET /deployments*, /environments*, /logs
write:deploymentsPOST /deployments, /cancel, /rollback
mcp:toolsevery read-only MCP tool
mcp:admindestructive MCP tools: ulex_reset_tenant, ulex_delete_*, ulex_rotate_*
scim:provisioninbound /scim/v2 writes, and reading SCIM bearer tokens
saml:consumePOST /connections/{id}/saml/acs
sso:impersonateimpersonation_only connections

Admin-only scopes, rejected at mint time: ulex:admin, mcp:admin, sso:impersonate.

A missing scope returns 403 insufficient_scope with the required scope in hint:

json
{
  "error": {
    "type": "permission_error",
    "code": "insufficient_scope",
    "message": "This credential requires the write:organizations scope.",
    "request_id": "req_01M3PSW9R0175NAW62NYR403R8",
    "retryable": false,
    "hint": "Request scope: write:organizations. See https://docs.ulexid.com/security/authorization#scopes",
    "docs_url": "https://docs.ulexid.com/api-reference/authentication#scopes"
  }
}

#Request headers

HeaderDirectionMeaning
Authorization: Bearer <key|token>requestrequired on everything except /health and discovery
Content-Type: application/jsonrequestrequired on bodies
Idempotency-Key: <uuid v4>requestdedupe a POST for 24 hours
X-Ulex-Request-Id: <string ≤64>requestcorrelation label, echoed, stored on the audit event
X-Ulex-Correlation-Id: <string ≤64>requestgroups related calls together across services
X-Ulex-Simulate: <mode>requestarm a failure on the next auth; requires allow_mocks: true or local mode
Accept: application/jsonrequestdefault
x-ulex-request-idresponsethe resolved request id, or the one you sent
x-ulex-correlation-idresponseechoed
x-ratelimit-limit / -remaining / -resetresponseunix seconds for reset
MCP-Protocol-VersionrequestMCP only, 2025-06-18
Mcp-Session-Idrequest/responseMCP only, from the initialize response
Ulex-Signatureinboundwebhook signature, t=<unix>,v1=<hex>
Note

X-Ulex-Request-Id and Idempotency-Key are not the same. Idempotency-Key deduplicates writes. X-Ulex-Request-Id is a label that shows up in the audit log so you can find every call your agent made. Use both, with different values.

#Token lifetimes

CredentialLifetimeRotation
API key90 days default, null = nevermanual; no overlap needed if you keep the old key until the new one is verified
Authorization code60 secondssingle use; a replay kills the grant
Access token (JWT, RS256)3,600 secondsnone; re-issue via refresh
Refresh token2,592,000 seconds (30 days)rotating — every use returns a new one; replaying an old one revokes the entire family
ID token3,600 secondsnone
Session86,400 s absolute, 604,800 s idlere-authenticate after 86,400 s
SAML assertion300 seconds NotOnOrAftern/a
SCIM bearer tokenuntil the directory is deletedPATCH /directories/{id} to reissue
Webhook secretuntil the webhook is deletedPOST /webhooks/{id}/rotate-secret equivalent via delete + recreate

Refresh-token reuse detection: if ulex sees a refresh token it has already rotated, it revokes the whole family_id and returns invalid_grant with hint: "Refresh token reuse detected; the token family has been revoked." Your app must then restart the flow from ulex_simulate_login or the authorization endpoint. This is correct behaviour, not a bug — it is how token theft is detected.

#Authenticated requests

#Authorization code with PKCE

bash
# 1. Redirect a human (or your test harness) here:
#    GET /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

# 2. Exchange the code.
curl -sS -X POST "$BASE/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"
}

#Refresh

bash
curl -sS -X POST "$BASE/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=refresh_token&
      refresh_token=rt_51KpXq8WvN0kTzRb7YcLd2mXe9Pf6Sg3AuV8&
      client_id=client_01M3PSV7J8TBSPHG95CYSEX32B&
      client_secret=cs_9fKq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8'

The response contains a new refresh token. Persist it atomically before using the new access token, or you will race a rotation and get invalid_grant.

#Client credentials

bash
curl -sS -X POST "$BASE/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=client_credentials&
      client_id=client_01M3PSV7J8TBSPHG95CYSEX32B&
      client_secret=cs_9fKq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8&
      scope=read:users%20read:organizations'
json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleV8wMU0zUFNWSkEwWVAyV0RQTTJSRFIxNU1HSCIsInR5cCI6IkpXVCJ9…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read:users read:organizations"
}

There is no refresh_token in a client-credentials response and there is no sub — the token is the machine. sub is the client_id.

#Token exchange (RFC 8693)

bash
curl -sS -X POST "$BASE/oauth2/token/exchange" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange&
      subject_token_type=urn:ietf:params:oauth:token-type:access_token&
      subject_token=eyJhbGciOiJSUzI1NiIsImtpZCI6ImtleV8wMU0zUFNWSkEwWVAyV0RQTTJSRFIxNU1HSCIsInR5cCI6IkpXVCJ9…&
      audience=client_01M3PSVV38V3BJQ4SDHQPT8WMJ&
      client_id=client_01M3PSV7J8TBSPHG95CYSEX32B&
      client_secret=cs_9fKq2WmB7yLt4NxZ1pRc6HdE0sJg3AuV8'

Returns a new access token scoped to audience with the same sub and a fresh sid. The target application must have urn:ietf:params:oauth:grant-type:token-exchange in grant_types or this returns unauthorized_client.

#Device authorization

bash
curl -sS -X POST "$BASE/oauth2/device/code" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'client_id=client_01M3PSV7J8TBSPHG95CYSEX32B&scope=openid%20profile'
json
{
  "device_code": "dc_7Kq2WmB4yLt4NxZ1pRc6HdE0sJg3AuV8",
  "user_code": "WXYZ-1234",
  "verification_uri": "https://ulexid.com/device",
  "verification_uri_complete": "https://ulexid.com/device?user_code=WXYZ-1234",
  "expires_in": 900,
  "interval": 5
}

Complete it headlessly by calling POST /simulator/authenticate with the user_code, or ulex_simulate_login with user_code. Then poll:

bash
curl -sS -X POST "$BASE/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=urn:ietf:params:oauth:grant-type:device_code&
      device_code=dc_7Kq2WmB4yLt4NxZ1pRc6HdE0sJg3AuV8&
      client_id=client_01M3PSV7J8TBSPHG95CYSEX32B'

While the user has not finished, this returns 400 authorization_pending with retryable: true and hint: "Retry after 5s." Honour the interval.

#MCP authentication

Two accepted methods.

#Static bearer token

bash
curl -sS -X POST "https://ulexid.com/api/v1/mcp" \
  -H "Authorization: Bearer ulex_sk_live_7Qm2KpLx9Tb4Ns8RfWy3Zc1Hjf6Ee0Au" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"agent","version":"1.0.0"}}}'

Requires the mcp:tools scope. Without it: 401 mcp_unauthorized. Read-only tools additionally need the matching read:* scope.

#OAuth 2.1 protected resource (RFC 9728)

bash
curl -sS https://ulexid.com/api/v1/.well-known/oauth-protected-resource
json
{
  "resource": "https://ulexid.com/api/v1",
  "authorization_servers": ["https://ulexid.com"],
  "scopes_supported": [
    "mcp:tools",
    "mcp:admin",
    "read:organizations", "write:organizations",
    "read:users", "write:users",
    "read:groups", "write:groups",
    "read:connections", "write:connections",
    "read:directories", "write:directories",
    "read:applications", "write:applications",
    "read:webhooks", "write:webhooks",
    "read:audit_logs",
    "read:deployments", "write:deployments"
  ],
  "bearer_methods_supported": ["header"],
  "resource_documentation": "https://docs.ulexid.com/agents/mcp-tools"
}

An unauthenticated POST /mcp returns 401 with:

http
HTTP/2 401 Unauthorized
www-authenticate: Bearer realm="ulex", error="invalid_token",
  error_description="An access token is required to call ulex MCP tools.",
  resource_metadata="https://ulexid.com/api/v1/.well-known/oauth-protected-resource"

Your client follows resource_metadata, discovers the authorization server, and runs the authorization-code-with-PKCE flow with resource=https://ulexid.com/api/v1 (RFC 8707). The resulting access token is a normal ulex access token — it works on REST too.

#stdio

bash
npx @ulexid/mcp-server

Reads ULEX_API_KEY from the environment. No token is ever passed on argv; that is deliberate, because argv is world-readable in /proc.

#Unauthenticated endpoints

These never require a credential:

text
GET /api/v1/health
GET /api/v1/status
GET /api/v1/.well-known/openid-configuration
GET /api/v1/.well-known/oauth-authorization-server
GET /api/v1/.well-known/oauth-protected-resource
GET /api/v1/oauth2/authorize
GET /api/v1/oauth2/keys
GET /api/v1/connections/{id}/saml/metadata
GET /api/v1/connections/{id}/saml/login

/oauth2/keys is public JWKS, as it must be. GET /connections/{id}/saml/metadata is public metadata, also as it must be — IdPs fetch it with no credential.

#Troubleshooting

StatuscodeCauseFix
401unauthenticatedno Authorization headeradd it
401invalid_api_keymalformed prefix or wrong lengthcopy the full key; do not add whitespace
401api_key_expiredpast expires_atmint a new one; do not retry
401api_key_revokedrevoked_at setexpected; mint a new one
401invalid_tokennot a JWT, or wrong issuercheck iss matches https://ulexid.com (or your local issuer)
401token_expiredexp in the pastrefresh
401token_revokedexplicitly revoked, or family reuserestart the login flow
403insufficient_scopescope missingread hint
403cross_tenantresource belongs to another tenantcheck the key's tenant
401ip_not_allowedip_allowlist mismatchadd the egress CIDR

Deeper: Common errors, Authorization, MCP troubleshooting.