Documentation base URLs use placeholder https://{your-tenant}.sso.id. Log in to show your tenant or custom domain.
Log in for Your Tenant URL
AI-Native Identity Engineering

AI Agent Protocol Playbooks

Turn hours of identity integration into a 60-second prompt. Copy these production-verified protocol specifications into Antigravity, Cursor, Claude Code, GitHub Copilot, or Windsurf to implement OpenID Connect (OIDC), OAuth 2.0, SAML 2.0, Password Grant, Passkeys (FIDO2), SCIM 2.0, and Management APIs with zero guesswork.

Real-World Engineering Story

Why Traditional SSO Docs Fail AI Coding Agents — And How We Fixed It

Meet Alex, a lead full-stack engineer migrating three products to SSO.ID v2: an Angular 16 SPA, a Node.js/ASP.NET microservice cluster, and a legacy enterprise B2B portal that requires SAML 2.0 and SCIM 2.0 user provisioning.

When Alex asks an AI coding assistant "Integrate SSO.ID login into my app" without context, the AI guesses generic OAuth URLs, omits PKCE S256 parameters, forgets B2B organization routing parameters (organizationId), or fails to use the tenant-scoped domain URL.

The SSO.ID v2 Solution: Every protocol below is packaged as a deterministic, self-contained AI Agent Specification containing exact endpoint URLs, HTTP verbs, request/response schemas, JWT claim structures, and security invariants from the real Auth.SSO.Id and Core.SSO.Id engines. Paste the prompt for your protocol into your AI agent, supply your CLIENT_ID, and watch it generate production-ready authentication code on the first run.

Step 1: Configure in Console

Open the SSO.ID v2 Admin Console ( /applications), create your application, and copy your Client ID, Client Secret, and Application ID.

Step 2: Copy Protocol Prompt

Choose your protocol below (OIDC, OAuth 2.0, SAML 2.0, Password Grant, Passkeys, or SCIM 2.0) and click Copy Prompt in the top-right corner of the dark prompt box.

Step 3: Paste into Your AI IDE

Paste the prompt into Cursor, Antigravity, Claude Code, or Copilot alongside your framework name (e.g., "Implement this in Next.js 14 App Router").

Flow Diagram AI Agent Protocol Implementation Workflow
flowchart LR DEV["Developer copies SSO.ID AI Prompt"] --> LLM["AI Coding Agent (Cursor / Claude / Copilot)"] LLM --> CODE["Generates Protocol Client (OIDC / SAML / SCIM)"] CODE --> AUTH["Auth.SSO.Id (Runtime Handshake)"] CODE --> API["{your-tenant}.sso.id/api (JWKS & Management API)"] AUTH --> PROD["Production Zero-Trust Integration"] API --> PROD
How developers leverage SSO.ID v2 protocol prompts with AI coding agents (Cursor, Copilot, Antigravity) to produce error-free authentication services.

Master SSO.ID v2 Architecture Context Prompt

If you are building a full-stack application or adding a custom cursor rule (.cursorrules, CLAUDE.md, or AGENTS.md) to your repository, drop this master specification into your project root so your AI agent understands the entire SSO.ID v2 ecosystem.

AGENTS.md / .cursorrules SSO.ID v2 Universal Architecture & Endpoint Specification
# SSO.ID v2 — Identity & Access Management Architecture Spec for AI Agents

## 1. Core Service Endpoints
- **Authorization & Protocol Server (`Auth.SSO.Id`)**: `https://{your-tenant}.sso.id/auth` (or Custom Domain e.g. `https://login.yourdomain.com`)
  - Handles browser redirects, OIDC Discovery (`/auth/.well-known/openid-configuration`), OAuth2 `/auth/oauth/authorize` & `/auth/oauth/token`, SAML 2.0 `/auth/Saml/Login` & `/auth/saml/acs`, and FIDO2 Passkeys `/auth/oauth/passkey/*`.
- **Core Management & Resource API (`Core.SSO.Id`)**: `https://{your-tenant}.sso.id/api`
  - Handles Management REST APIs (`/api/applications`, `/api/users`, `/api/roles`, `/api/organizations`, `/api/connections`, `/api/settings/tenant`, `/api/audit-logs`), SCIM 2.0 (`/api/scim/v2`), and Direct OAuth2 Token Issuance (`/api/oauth2/token`).
- **Admin Console & App Launcher (`angular.sso.id`)**: `https://{your-tenant}.sso.id`

## 2. Multi-Tenant & Regional Headers (For Core Management API Calls)
When calling `https://{your-tenant}.sso.id/api/*` endpoints:
- `Authorization: Bearer ` (Required for authenticated API calls; tenant context is embedded directly in the JWT claims and/or detected from the tenant domain URL)

## 3. 4-Tier Policy Inheritance Cascade
SSO.ID v2 evaluates authentication, branding, token lifetimes, and MFA policies across 4 hierarchical tiers:
`Tenant (/settings)` -> `Application (/applications)` -> `Organization (/organizations)` -> `Organization Unit (/organization-units)`
Each lower tier has explicit override flags (`overrideGeneral`, `overrideBranding`, `overrideSecurity`, `overrideTokens`, `overrideMfa`). When an override flag is `true` on an Organization or Organization Unit, passing `organizationId` or `organizationUnitId` to `/auth/oauth/authorize` dynamically enforces that tier's branding, IdP connections, token lifetimes, and MFA rules.

## 4. Discovery & Cryptographic Verification
- **OIDC Discovery Document**: `GET https://{your-tenant}.sso.id/auth/.well-known/openid-configuration?appId=`
- **JWKS Public Keys**: `GET https://{your-tenant}.sso.id/auth/.well-known/jwks.json?appId=`
- **Supported Signing Algorithms**: `RS256` (default asymmetric), `RS384`, `RS512`, `ES256`, `HS256`.

Protocol 1: OpenID Connect (OIDC) + PKCE

Best for: Single-Page Applications (Angular, React, Vue), Modern Full-Stack Web Apps (Next.js, Nuxt, SvelteKit, ASP.NET Core MVC), and Native Mobile Apps (iOS, Android, Flutter, React Native). Uses Authorization Code Flow with Proof Key for Code Exchange (S256).

AI Agent Prompt OpenID Connect (OIDC) Authorization Code + PKCE Integration
You are an expert identity engineer. Implement OpenID Connect (OIDC) Authentication with PKCE (`S256`) using **SSO.ID v2** in my application.

### 1. SSO.ID v2 Configuration Constants
- `SSO_AUTH_BASE_URL`: `https://{your-tenant}.sso.id/auth` (or custom tenant domain)
- `SSO_API_BASE_URL`: `https://{your-tenant}.sso.id/api`
- `SSO_APP_ID`: ``
- `SSO_CLIENT_ID`: ``
- `SSO_CLIENT_SECRET`: `` (Omit in public SPA/Mobile clients)
- `SSO_REDIRECT_URI`: ``
- `SSO_POST_LOGOUT_REDIRECT_URI`: ``

### 2. Discovery & JWKS Endpoints
- OpenID Configuration: `GET https://{your-tenant}.sso.id/auth/.well-known/openid-configuration?appId=${SSO_APP_ID}`
- JWKS Endpoint: `GET https://{your-tenant}.sso.id/auth/.well-known/jwks.json?appId=${SSO_APP_ID}`

### 3. Step-by-Step OIDC + PKCE Flow to Implement
1. **Generate PKCE & State**:
   - Generate a cryptographically random `code_verifier` (43-128 chars, URL-safe).
   - Compute `code_challenge = BASE64URL(SHA256(ASCII(code_verifier)))`.
   - Generate random `state` and `nonce` strings and store `{ code_verifier, state, nonce }` in `sessionStorage` or an `HttpOnly` cookie.

2. **Redirect to Authorization Endpoint (`GET https://{your-tenant}.sso.id/auth/oauth/authorize`)**:
   Query Parameters:
   - `client_id`: `${SSO_CLIENT_ID}`
   - `response_type`: `code`
   - `redirect_uri`: `${SSO_REDIRECT_URI}`
   - `scope`: `openid profile email roles offline_access`
   - `state`: `${state}`
   - `code_challenge`: `${code_challenge}`
   - `code_challenge_method`: `S256`
   - Optional B2B / Enterprise routing params (if applicable):
     - `organizationId`: `` (Routes login to a specific B2B customer organization's branding/MFA)
     - `organizationUnitId`: `` (Routes login to a specific sub-department)
     - `connectionId`: `` (Bypasses login chooser and jumps straight to an external OIDC/SAML/OAuth2 IdP)
     - `login_hint`: ``

3. **Handle Callback & Exchange Code for Tokens (`POST https://{your-tenant}.sso.id/auth/oauth/token`)**:
   - Verify `state` matches stored state.
   - Send `POST https://{your-tenant}.sso.id/auth/oauth/token` with `Content-Type: application/x-www-form-urlencoded`:
     - `grant_type=authorization_code`
     - `client_id=${SSO_CLIENT_ID}`
     - `client_secret=${SSO_CLIENT_SECRET}` (if confidential backend)
     - `code=${authorization_code}`
     - `redirect_uri=${SSO_REDIRECT_URI}`
     - `code_verifier=${code_verifier}`
   - Expected JSON Response:
     ```json
     {
       "access_token": "eyJhbGciOiJSUzI1NiIs...",
       "id_token": "eyJhbGciOiJSUzI1NiIs...",
       "refresh_token": "def50200...",
       "token_type": "Bearer",
       "expires_in": 3600,
       "scope": "openid profile email roles offline_access"
     }
     ```

4. **Fetch User Profile (`GET https://{your-tenant}.sso.id/auth/oauth/userinfo`)**:
   - Pass header `Authorization: Bearer ${access_token}`.
   - Returns standard OIDC claims (`sub`, `name`, `given_name`, `family_name`, `email`, `email_verified`, `picture`, `roles`, `tenant_id`, `org_id`).

5. **Token Refresh (`POST https://{your-tenant}.sso.id/auth/oauth/token`)**:
   - Send `grant_type=refresh_token&client_id=${SSO_CLIENT_ID}&refresh_token=${refresh_token}`.

6. **RP-Initiated Logout (`GET https://{your-tenant}.sso.id/auth/oauth/logout`)**:
   - Redirect to `https://{your-tenant}.sso.id/auth/oauth/logout?id_token_hint=${id_token}&post_logout_redirect_uri=${encodeURIComponent(SSO_POST_LOGOUT_REDIRECT_URI)}`.

Please generate clean, modular, production-ready code for my framework with full error handling, automatic silent token refresh, and typed user session state.

Protocol 2: OAuth 2.0 (Confidential Web & Machine-to-Machine client_credentials)

Best for: Backend microservices, cron jobs, daemon workers, and API gateways that need to authenticate service-to-service without a browser (client_credentials), or server-side web apps exchanging authorization codes using HTTP Basic Auth or POST body credentials.

AI Agent Prompt OAuth 2.0 M2M Client Credentials & Token Refresh Specification
You are an expert backend systems engineer. Implement an OAuth 2.0 Client Credentials (`client_credentials`) and Token Management client for **SSO.ID v2** with automatic in-memory caching and proactive token renewal before expiry.

### 1. Endpoints Supported by SSO.ID v2
SSO.ID v2 supports token issuance on both the Protocol Server and the Core API:
- Primary Protocol Token Endpoint: `POST https://{your-tenant}.sso.id/auth/oauth/token`
- Direct Core API Token Endpoint: `POST https://{your-tenant}.sso.id/api/oauth2/token`

### 2. Authentication Methods Supported
You may authenticate the confidential client using either:
- **Method A (HTTP Basic Header)**: `Authorization: Basic BASE64(:)`
- **Method B (Form / JSON Body)**: Include `client_id` and `client_secret` in the request body (`application/x-www-form-urlencoded` or `application/json`).

### 3. Machine-to-Machine (`client_credentials`) Request
```http
POST https://{your-tenant}.sso.id/auth/oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=&client_secret=&scope=api:read api:write
```

### 4. Token Response Payload
```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "api:read api:write"
}
```

### 5. Implementation Requirements
1. Create a singleton `SsoIdTokenClient` service that requests an `access_token` using `grant_type=client_credentials`.
2. Cache the token in memory and automatically refresh it 60 seconds before `expires_in` elapses (with concurrency locking so parallel requests do not trigger duplicate token calls).
3. Provide an HTTP client interceptor/middleware that attaches `Authorization: Bearer ` to outbound requests (tenant context is embedded in the token and domain URL) to `https://{your-tenant}.sso.id/api` or downstream microservices.
4. Retry once on `401 Unauthorized` by evicting the cached token and fetching a fresh token.

Protocol 3: SAML 2.0 Enterprise Federation (IdP & SP Flows)

Best for: Enterprise B2B applications, legacy ERP/CRM integrations, or connecting Workforce Identity Providers (Okta, Microsoft Entra ID / Azure AD, PingFederate, OneLogin, Google Workspace) where SSO.ID acts as either the SAML 2.0 Identity Provider (IdP) for your application or the SAML 2.0 Service Provider (SP) federating with an external enterprise IdP.

AI Agent Prompt SAML 2.0 Service Provider (SP) & Identity Provider (IdP) Integration
You are an enterprise security engineer. Implement **SAML 2.0 Single Sign-On (SSO) and Single Logout (SLO)** integrating with **SSO.ID v2**.

### Scenario A: SSO.ID v2 as the SAML 2.0 Identity Provider (Your App is the SAML SP)
Use these endpoints on `https://{your-tenant}.sso.id/auth` to configure your application's SAML SP library (e.g., `passport-saml`, `@node-saml/node-saml`, `Sustainsys.Saml2`, `ITfoxtec.Identity.Saml2`, `python3-saml`, or Spring Security SAML):

1. **IdP Metadata XML Endpoint (Auto-Configuration)**:
   - `GET https://{your-tenant}.sso.id/auth/saml/metadata?appId=`
   - Base64-encoded IdP Metadata alternative: `GET https://{your-tenant}.sso.id/auth/saml/GetIDPMetadataBase64?appId=`
   - Core API Application Metadata Lookup: `GET https://{your-tenant}.sso.id/api/applications/metadata?id=`
   - Core API Signing Certificate Download: `GET https://{your-tenant}.sso.id/api/applications/certificate?id=`

2. **IdP Single Sign-On (SSO) Service URL**:
   - `https://{your-tenant}.sso.id/auth/Saml/Login`
   - Supports both **HTTP-Redirect** (`GET /auth/Saml/Login?SAMLRequest=...&RelayState=...`) and **HTTP-POST** (`POST /auth/Saml/Login` with form field `SAMLRequest` and `RelayState`).

3. **IdP Single Logout (SLO) Service URL**:
   - `GET` or `POST` `https://{your-tenant}.sso.id/auth/saml/logout` (Also aliased at `/auth/saml/slo`).

4. **Expected SAML 2.0 Assertion Details**:
   - `NameIDFormat`: `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress` or `urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`
   - Signed XML Assertion (`rsa-sha256` / `sha256` digest).
   - Standard Attribute Statements mapped by SSO.ID:
     - `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier` (User ID)
     - `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress` (Email)
     - `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname` (First Name)
     - `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname` (Last Name)
     - `http://schemas.microsoft.com/ws/2008/06/identity/claims/role` (Assigned Application Roles)

### Scenario B: SSO.ID v2 as the SAML 2.0 Service Provider (Federating External Okta / Azure AD IdP into SSO.ID)
When configuring an external enterprise IdP to send SAML assertions *into* SSO.ID v2:
- **Assertion Consumer Service (ACS) URL**: `POST https://{your-tenant}.sso.id/auth/saml/acs` (or `https://{your-tenant}.sso.id/auth/saml/acs`)
- **SP Metadata XML URL**: `GET https://{your-tenant}.sso.id/auth/Saml/SPMetadata` or `GET https://{your-tenant}.sso.id/api/connections/sp-metadata`
- **SP X.509 Certificate Download**: `GET https://{your-tenant}.sso.id/api/connections/sp-certificate`

### Implementation Task
Generate the complete SAML 2.0 SP authentication module for my application, including:
1. Dynamic IdP Metadata loading from `https://{your-tenant}.sso.id/auth/saml/metadata?appId=`.
2. SP Metadata generation endpoint (`/saml/metadata`) so I can upload or paste my SP Entity ID and ACS URL into the SSO.ID Admin Console (`/applications` -> Application Settings -> Protocol: SAML 2.0).
3. Login initiation route (`/login/sso`) generating a signed `AuthnRequest` with `RelayState`.
4. Assertion Consumer Service route (`POST /saml/acs`) validating the XML signature, `AudienceRestriction`, `NotBefore`/`NotOnOrAfter` conditions, and `InResponseTo` replay protection, then establishing a local user session.

Protocol 4: Direct / Resource Owner Password Grant (grant_type=password)

Best for: Trusted first-party native apps, CLI tools, POS terminals, or embedded custom login forms where your backend collects the username/password directly and exchanges them for SSO.ID v2 JWT tokens without a browser redirect.

AI Agent Prompt Direct Password Grant (grant_type=password) Integration
You are a senior security developer. Implement Direct Password Grant (`grant_type=password`) authentication against **SSO.ID v2** for our trusted first-party client.

### 1. Prerequisites in SSO.ID v2 Admin Console
- In `/applications` -> Application Settings -> **General / Protocol**, ensure **Password** (or OAuth2/OIDC with Password grant enabled) is selected.
- Copy the `Client ID` and `Client Secret`.

### 2. Token Request (`POST https://{your-tenant}.sso.id/auth/oauth/token` or `POST https://{your-tenant}.sso.id/api/oauth2/token`)
Both `application/x-www-form-urlencoded` and `application/json` payloads are supported:
```http
POST https://{your-tenant}.sso.id/auth/oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=&client_secret=&username=&password=&scope=openid profile email roles offline_access
```

### 3. Handling Responses & Error Codes
- **200 OK (Authenticated)**:
  ```json
  {
    "access_token": "eyJhbGciOiJSUzI1NiIs...",
    "refresh_token": "def50200...",
    "id_token": "eyJhbGciOiJSUzI1NiIs...",
    "token_type": "Bearer",
    "expires_in": 3600
  }
  ```
- **400 Bad Request (`invalid_grant`)**: Invalid username or password, or account locked due to brute-force lockout policy (`maxFailedLoginAttempts`).
- **403 Forbidden (`mfa_required`)**: If the user or application enforces mandatory Multi-Factor Authentication, guide the user to interactive OIDC flow (`/auth/oauth/authorize`) or step-up MFA verification.

### 4. Implementation Task
Build a login service and UI form that:
1. Submits credentials over HTTPS to our backend proxy (or directly to `/auth/oauth/token` if a native mobile/CLI app).
2. Stores the `access_token` and `refresh_token` securely (`HttpOnly` cookies for web, Keychain/Keystore for mobile).
3. Fetches the user's assigned application menus and roles via `GET https://{your-tenant}.sso.id/auth/oauth/userinfo` and `GET https://{your-tenant}.sso.id/api/users/self`.

Protocol 5: FIDO2 / WebAuthn Passkeys (Passwordless Biometrics)

Best for: Phishing-resistant passwordless authentication using Apple FaceID/TouchID, Windows Hello, Android Biometrics, or YubiKey hardware security keys via Auth.SSO.Id's native WebAuthn ceremony endpoints.

AI Agent Prompt FIDO2 / WebAuthn Passkey Registration & Passwordless Sign-In
You are a WebAuthn / FIDO2 specialist. Integrate **SSO.ID v2 Passkey Registration and Passwordless Authentication** using the browser's `navigator.credentials` WebAuthn API and `https://{your-tenant}.sso.id/auth/oauth/passkey/*` endpoints.

### 1. Passkey Enrollment (Registration Ceremony for Logged-In Users)
1. **Begin Registration (`POST https://{your-tenant}.sso.id/auth/oauth/passkey/register-begin`)**:
   - Send authenticated request with user identifier / session.
   - Receives `PublicKeyCredentialCreationOptions` (`challenge`, `rp`, `user`, `pubKeyCredParams`, `authenticatorSelection`, `excludeCredentials`).
2. **Browser Biometric Ceremony**:
   - Convert Base64URL `challenge` and `user.id` to `Uint8Array`.
   - Call `const credential = await navigator.credentials.create({ publicKey: options })`.
3. **Complete Registration (`POST https://{your-tenant}.sso.id/auth/oauth/passkey/register-complete`)**:
   - Encode `credential.id`, `credential.rawId`, `response.attestationObject`, and `response.clientDataJSON` as Base64URL and POST to `/auth/oauth/passkey/register-complete`.

### 2. Passwordless Sign-In (Assertion Ceremony)
1. **Begin Authentication (`POST https://{your-tenant}.sso.id/auth/oauth/passkey/auth-begin`)**:
   - Optional payload: `{ "username": "[email protected]", "clientId": "" }` (or empty for discoverable resident passkeys).
   - Receives `PublicKeyCredentialRequestOptions` (`challenge`, `rpId`, `allowCredentials`, `userVerification`).
2. **Browser Assertion Ceremony**:
   - Convert Base64URL `challenge` (and `allowCredentials[].id`) to `Uint8Array`.
   - Call `const assertion = await navigator.credentials.get({ publicKey: options })`.
3. **Complete Authentication (`POST https://{your-tenant}.sso.id/auth/oauth/passkey/auth-complete`)**:
   - Send Base64URL-encoded `id`, `rawId`, `response.authenticatorData`, `response.clientDataJSON`, `response.signature`, and `response.userHandle` to `/auth/oauth/passkey/auth-complete`.
   - Receives authenticated redirect / token grant.

Please generate a TypeScript helper utility (`passkeyAuth.ts`) that handles Base64URL <-> ArrayBuffer conversions and implements both `registerPasskey()` and `authenticateWithPasskey()`.

Protocol 6: SCIM 2.0 Automated User & Group Provisioning

Best for: Automating employee onboarding, attribute updates, group membership syncing, and instant offboarding (suspend / revoke / delete) between HRIS/IdP systems (Okta, Microsoft Entra ID, Rippling, Workday) and SSO.ID v2.

AI Agent Prompt SCIM 2.0 RFC 7643 / RFC 7644 Provisioning Client & Sync Engine
You are an enterprise identity provisioning engineer. Build a **SCIM 2.0 (RFC 7643 / RFC 7644)** client that synchronizes Users and Groups with **SSO.ID v2**.

### 1. Base URLs & Authentication
- **Tenant-Wide SCIM 2.0 Base URL**: `https://{your-tenant}.sso.id/api/scim/v2`
- **Connection-Scoped SCIM 2.0 Base URL**: `https://{your-tenant}.sso.id/api/scim/v2/connections/{connectionId}`
- **Authentication**: `Authorization: Bearer `
  (Generated in the SSO.ID Admin Console under `/settings` -> **Provisioning (SCIM 2.0)** -> `POST /api/settings/tenant/scim/token`, or under `/connections` -> Connection Settings -> **Provisioning** tab).
- **Content-Type**: `application/scim+json` (or `application/json`)

### 2. Discovery Endpoints
- `GET /ServiceProviderConfig` — Returns supported SCIM operations (`patch`, `bulk`, `filter`, `changePassword`, `sort`, `etag`).
- `GET /Schemas` — Returns `urn:ietf:params:scim:schemas:core:2.0:User` and `urn:ietf:params:scim:schemas:core:2.0:Group`.
- `GET /ResourceTypes` — Returns `/Users` and `/Groups` resource definitions.

### 3. SCIM 2.0 User Lifecycle Endpoints (`/Users`)
- **List / Filter Users**: `GET /Users?filter=userName eq "[email protected]"&startIndex=1&count=50`
- **Get User**: `GET /Users/{id}`
- **Create User (`POST /Users`)**:
  ```json
  {
    "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
    "externalId": "emp-90210",
    "userName": "[email protected]",
    "name": {
      "givenName": "Alice",
      "familyName": "Vance",
      "formatted": "Alice Vance"
    },
    "emails": [
      { "value": "[email protected]", "type": "work", "primary": true }
    ],
    "active": true
  }
  ```
- **Replace User (`PUT /Users/{id}`)**: Full replacement of user attributes.
- **Partial Update / Deactivate User (`PATCH /Users/{id}`)**:
  ```json
  {
    "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
    "Operations": [
      { "op": "replace", "path": "active", "value": false }
    ]
  }
  ```
- **Delete / Deprovision User**: `DELETE /Users/{id}` (Executes configured deprovision action: `suspend`, `revoke` sessions, or permanent `delete`).

### 4. SCIM 2.0 Group Lifecycle Endpoints (`/Groups`)
- `GET /Groups`, `GET /Groups/{id}`, `POST /Groups`, `PUT /Groups/{id}`, `DELETE /Groups/{id}` using schema `urn:ietf:params:scim:schemas:core:2.0:Group` with `displayName` and `members: [{ "value": "", "display": "Alice Vance" }]`.

Please implement a resilient SCIM 2.0 provisioning service with idempotent user lookup (`filter=userName eq ...`), creation, attribute updates, group membership sync, and soft/hard deprovisioning.

Protocol 7: Backend API JWT Validation & Dynamic Menu/API RBAC

Best for: Securing your backend APIs (ASP.NET Core, Node.js/Express/NestJS, Python FastAPI, Go, Java Spring Boot) by verifying SSO.ID RS256 signatures via JWKS and enforcing Role-Based Access Control (RBAC) across both Application Menus and Application API Endpoints.

AI Agent Prompt Backend JWT Signature Verification (JWKS) & Dynamic RBAC Middleware
You are a principal application security engineer. Implement **JWT Bearer Authentication and Fine-Grained RBAC Authorization Middleware** for my backend API using **SSO.ID v2**.

### 1. JWKS & Token Validation Rules
- **Issuer (`iss`)**: `https://{your-tenant}.sso.id/auth` (or custom domain)
- **JWKS URI**: `https://{your-tenant}.sso.id/auth/.well-known/jwks.json?appId=`
- **Algorithms**: `RS256` (default), `RS384`, `RS512`, `ES256`
- **Validation Requirements**:
  1. Fetch and cache public signing keys by `kid` from the JWKS URI (with automatic rotation support when a new `kid` is encountered via `/api/signing-keys/rotate`).
  2. Validate token signature, `exp` (expiration), `nbf` (not before), `iss` (issuer), and `aud` (audience = `` or ``).

### 2. SSO.ID v2 Dynamic RBAC Model (Menus + APIs)
In SSO.ID v2 (`/role-management` and `/applications`), each Application defines:
1. **Hierarchical App Pages / Menus** (`GET https://{your-tenant}.sso.id/api/applications/{appId}/menus`) with granular CRUD flags per Role (`view`, `add`, `update`, `delete`) configured via `PUT /api/roles/{roleId}/applications/{appId}/menu-access`.
2. **Application API Endpoints** (`GET https://{your-tenant}.sso.id/api/applications/{appId}/apis`) mapped to Roles via `PUT /api/roles/{roleId}/applications/{appId}/api-access`.

### 3. Implementation Task
1. Create an authentication middleware/guard that validates incoming `Authorization: Bearer ` headers against SSO.ID's JWKS endpoint and attaches the decoded claims (`sub`, `email`, `roles`, `tenant_id`, `org_id`) to the request context.
2. Create an authorization decorator/middleware `requireRole(...roles)` and `requireMenuPermission(menuCode, action: 'view' | 'add' | 'update' | 'delete')`.
3. Provide a frontend helper endpoint or hook that fetches the authenticated user's permitted navigation tree and CRUD permissions so the UI dynamically hides unauthorized sidebar items and action buttons.

Protocol 8: Official SSO.ID SDKs (@sso-id/* & SsoId.*)

Best for: Instructing AI coding agents to use SSO.ID's official first-party SDKs (@sso-id/spa-js, @sso-id/react, @sso-id/angular, @sso-id/vue, @sso-id/nextjs, @sso-id/express, @sso-id/node, SsoId.AspNetCore, SsoId.ManagementApi, sso-id-python) instead of writing raw OIDC/PKCE boilerplate.

AI Agent Prompt Official SSO.ID SDK Integration Guide
You are integrating authentication and RBAC using **official SSO.ID SDKs** (see `/v2/libraries`).

### Package Selection
- **React**: `npm install @sso-id/react` -> wrap root with `<SsoIdProvider domain="..." clientId="..." clientSecret="..." redirectUri="...">`, consume `useSsoId()`, and guard UI with `<RequirePermission pagePath="/users" action="read">`.
- **Angular**: `npm install @sso-id/angular` -> register `provideSsoId({ domain, clientId, clientSecret, redirectUri })`, `withInterceptors([ssoIdHttpInterceptor])`, and `canActivate: [ssoIdAuthGuard]`.
- **Vue 3**: `npm install @sso-id/vue` -> `app.use(createSsoId({ domain, clientId, clientSecret, redirectUri }))` and `useSsoId()`.
- **Next.js App Router**: `npm install @sso-id/nextjs` -> `createSsoIdRouteHandler` at `/api/auth/[...ssoid]/route.ts` and `withMiddlewareAuthRequired` in `middleware.ts`.
- **Node.js / Express**: `npm install @sso-id/node` -> `verifyAccessToken(token, { domain, audience })` and `new ManagementClient({ domain, clientId, clientSecret, apiBaseUrl })`. Use `mgmt.withUserToken(req.headers.authorization)` to forward user tokens and enforce user-level App Pages RBAC (`listAllowedMenus(userId)`).
- **Starter Templates**: `npx @sso-id/cli create <template>` -> Scaffold 10 full-featured starters (Next.js, React SPA, Vue SPA, Angular SPA, Express, .NET, Python FastAPI, Go Gin, PHP Laravel, React Native) with App Pages navigation trees, strict 403 guards, and bidirectional SCIM 2.0 provisioning.
- **ASP.NET Core (.NET 8+)**: `dotnet add package SsoId.AspNetCore` -> `builder.Services.AddSsoIdWebApp(...)` or `AddSsoIdApi(...)` and `[SsoPermission("/users", "read")]`.
- **Python**: `pip install sso-id-python` -> `SsoIdClient` and `SsoManagementClient`.

### Important SSO.ID Endpoints
- Discovery: `https://<domain>/auth/.well-known/openid-configuration`
- JWKS: `https://<domain>/auth/.well-known/jwks.json`
- OAuth Authorize / Token / UserInfo / Logout: `/auth/oauth/authorize`, `/auth/oauth/token`, `/auth/oauth/userinfo`, `/auth/oauth/logout`

8. AI Agent Identity Governance (Admin Console & REST API)

Treat autonomous AI agents, coding copilots, and MCP tool clients as first-class Non-Human Identities (NHIs). Manage the complete governance lifecycle in the Admin Console ( /ai-agents) or automate it via the /api/ai-agents REST API.

1. Discovery & Human Ownership

Catalog every AI agent, run Shadow AI Discovery Scans to detect unmanaged OAuth/M2M bots, flag orphaned agents with no human sponsor, and compute live risk scores (0–100).

2. MCP Gateway & JIT Tokens

Enforce least-privilege scopes, authorized MCP servers, and API route allowlists. Mint short-lived JIT Agent JWTs bound to a human owner and delegation mode (OnBehalfOfUser, HumanInTheLoop, AutonomousM2M).

3. HITL, Certifications & Kill-Switch

Route elevated scope requests for human approval, run periodic Access Certification Campaigns, stream full agent audit telemetry, and trigger an instant Kill-Switch to revoke all active tokens.

REST API Endpoints & Complete Request/Response Schemas (/api/ai-agents)

All AI Agent Identity Governance endpoints require Authorization: Bearer <ACCESS_TOKEN> (Tenant Admin / Owner or Applications permission). Tenant context is resolved automatically from the JWT claims and tenant domain URL.

GET /api/ai-agents
Bearer JWT

Returns the tenant's AI Agent Governance posture KPI summary alongside all registered, discovered, and orphaned AI agent identities.

Request Parameters

No path, query, or body parameters required. Tenant scope is derived from the Bearer token and domain URL.

Response Schema (200 OK)
FieldTypeDescription
summaryobjectAggregated governance posture KPIs for the current tenant.
summary.totalAgentsintegerTotal AI agents registered or discovered in the tenant.
summary.activeAgentsintegerAgents currently in Active status.
summary.shadowAgentsintegerAgents discovered via Shadow_AI_Scan.
summary.orphanedAgentsintegerAgents missing an accountable human owner (ownerEmail empty or status Orphaned).
summary.highRiskAgentsintegerAgents with riskLevel of High or Critical.
summary.revokedAgentsintegerAgents in Revoked or Suspended status.
summary.pendingAccessRequestsintegerCount of HITL elevated scope requests awaiting review.
summary.dueCertificationsintegerCount of pending access certification reviews.
agentsAiAgentDTO[]Full array of AI agent identity objects ordered by createdOn DESC.
POST /api/ai-agents | PUT /api/ai-agents/{agentId}
Bearer JWT

Register a new governed AI agent identity (201 Created) or update an existing agent's governance policy, human owner, scopes, or MCP allowlist (200 OK). Risk score and risk level are automatically recalculated on every save.

Request Parameters
ParameterInTypeRequiredDescription
agentIdPathstringPUT OnlyUnique agent identifier (e.g. agt_7a2bb83f901a4e). Auto-generated on POST if omitted.
nameBodystring (max 150)RequiredDisplay name of the AI agent (e.g. Support Triage Copilot).
descriptionBodystring (max 500)OptionalOperational purpose and security boundary description.
agentTypeBodystringOptionalAutonomous (default), Copilot, Workflow, MCP_Client, or Customer_Facing.
modelProviderBodystringOptionalOpenAI (default), Anthropic, Google Gemini, LangChain, CrewAI, or Custom.
ownerUserIdBodystringOptionalDirectory User ID of the accountable human sponsor.
ownerEmailBodystringRecommendedEmail of the human owner. Leaving empty automatically flags the agent as Orphaned and adds +35 risk score.
ownerNameBodystringOptionalDisplay name of the human owner.
statusBodystringOptionalActive (default), Suspended, Revoked, PendingReview, or Orphaned.
clientIdBodystringOptionalLinked OAuth 2.0 / OIDC Client ID boundary.
applicationIdBodystringOptionalLinked SSO.ID Application ID.
delegationModeBodystringOptionalOnBehalfOfUser (default), HumanInTheLoop, or AutonomousM2M.
allowedScopesBodystringOptionalComma-separated least-privilege scopes (default: profile:read). Wildcards/admin/delete increase risk score.
allowedMcpServersBodystringOptionalComma-separated authorized MCP server URIs (e.g. mcp://crm-readonly, mcp://jira-triage).
allowedApiEndpointsBodystringOptionalComma-separated authorized API route paths (e.g. /api/users, /api/organizations).
maxTokenTtlMinutesBodyintegerOptionalMaximum lifetime (in minutes) for issued JIT tokens (default: 15). Values > 60 increase risk score.
requireHumanApprovalForWriteBodybooleanOptionalEnforces HITL approval for state-mutating tool/API calls (default: true).
Response Schema (AiAgentDTO — returned by GET /{agentId}, POST, PUT)
FieldTypeDescription
agentIdstringUnique agent identifier (agt_...).
tenantIduuidOwning tenant GUID.
name, description, agentType, modelProviderstringAgent identity metadata.
ownerUserId, ownerEmail, ownerNamestring?Accountable human sponsor details.
statusstringActive | Suspended | Revoked | PendingReview | Orphaned.
discoverySourcestringManual | Shadow_AI_Scan | OAuth_Grant | MCP_Gateway.
riskScoreinteger (0–100)Computed governance risk score.
riskLevelstringLow (<25), Medium (25–49), High (50–74), or Critical (75–100).
delegationMode, allowedScopes, allowedMcpServers, allowedApiEndpointsstringActive least-privilege access boundaries.
maxTokenTtlMinutesintegerCapped JIT token TTL in minutes.
requireHumanApprovalForWritebooleanWhether write/delete actions require HITL approval.
lastCertifiedOn, nextCertificationDueOn, lastActiveOn, createdOn, lastModifiedOndatetime?Lifecycle, certification, and activity UTC timestamps.
createdBystring?Email of admin who registered the agent.
GET /api/ai-agents/{agentId} | DELETE /api/ai-agents/{agentId}
Bearer JWT

Fetch a single AI agent's full governance record (GET → AiAgentDTO) or permanently decommission and remove the agent identity (DELETE → { "deleted": true, "agentId": "agt_..." }).

Request Parameters
ParameterInTypeRequiredDescription
agentIdPathstringRequiredTarget AI agent ID (agt_...). Returns 404 Not Found if not in caller's tenant.
POST /api/ai-agents/{agentId}/issue-jit-token
Bearer JWT

Mints a short-lived, least-privilege JIT Agent JWT. Fails with 400 Bad Request if the agent is Revoked/Suspended or if requested scopes fall outside allowedScopes.

Request Parameters
ParameterInTypeRequiredDescription
agentIdPathstringRequiredTarget active AI agent ID.
requestedScopesBodystringOptionalSpace/comma-separated scopes to request. Intersected with agent's allowedScopes. Defaults to all allowed scopes.
ttlMinutesBodyintegerOptionalRequested lifetime in minutes. Automatically capped at agent.maxTokenTtlMinutes.
targetMcpServerBodystringOptionalTarget MCP server URI embedded as the JWT aud and mcp_server claim.
Response Schema (200 OK)
FieldTypeDescription
accessTokenstring (JWT)Signed short-lived JWT containing claims: sub, jti, token_use="ai_agent_jit", agent_id, agent_name, agent_type, tenant_id, delegation_mode, human_owner, scope, hitl_write_required, and optional mcp_server.
tokenTypestringAlways "Bearer".
expiresInSecondsintegerToken validity duration in seconds (e.g. 600 for 10m).
grantedScopesstringSpace-delimited least-privilege scopes actually granted.
delegationModestringDelegation mode bound to the token.
agentIdstringAgent identifier.
humanOwnerstring?Accountable human sponsor email.
expiresAtUtcdatetimeExact UTC expiration timestamp.
POST /api/ai-agents/{agentId}/revoke | POST /api/ai-agents/{agentId}/reactivate
Bearer JWT

Emergency Kill-Switch: immediately transitions an agent to Revoked (or Suspended), invalidating active token issuance and logging a critical audit event. Use /reactivate to restore Active status after review. Both return the updated AiAgentDTO.

Request Parameters (/revoke)
ParameterInTypeRequiredDescription
agentIdPathstringRequiredTarget AI agent ID.
reasonBodystringOptionalIncident or security reason recorded in the audit log.
suspendOnlyBodybooleanOptionalIf true, sets status to Suspended; if false (default), sets status to Revoked.
POST /api/ai-agents/discover
Bearer JWT

Runs a Shadow AI & Orphaned Agent Discovery Scan across tenant OAuth/M2M applications, auto-registering unmanaged agentic apps as PendingReview and flagging ownerless agents as Orphaned (Critical risk).

Response Schema (200 OK)
FieldTypeDescription
scannedApplicationsintegerNumber of tenant OAuth/M2M applications inspected.
newlyDiscoveredShadowAgentsintegerCount of unmanaged AI/Bot/MCP integrations newly added to the registry.
orphanedAgentsFlaggedintegerCount of active agents missing an owner that were flagged as Orphaned.
scannedAtUtcdatetimeUTC timestamp of scan completion.
discoveredAgentsAiAgentDTO[]Array of newly discovered shadow agent objects.
GET /api/ai-agents/access-requests | POST /api/ai-agents/{agentId}/access-requests | POST /api/ai-agents/access-requests/{requestId}/review
Bearer JWT

Human-in-the-Loop (HITL) elevated access workflow. List all requests, submit a new elevated scope/MCP server request for an agent, or approve/deny a pending request (approved scopes and MCP servers automatically merge into the agent's policy).

Request Parameters
ParameterIn / EndpointTypeRequiredDescription
agentIdPath (Create)stringRequiredTarget AI agent requesting elevated access.
requestedScopesBody (Create)stringRequiredComma-separated scopes requested (e.g. orders:write, billing:read).
requestedMcpServersBody (Create)stringOptionalComma-separated additional MCP servers requested.
justificationBody (Create)stringOptionalBusiness justification for the human approver.
requestIdPath (Review)stringRequiredAccess request ID (req_...) to review.
decisionBody (Review)stringRequiredApproved or Denied.
reviewNotesBody (Review)stringOptionalReviewer decision comments recorded in audit logs.
Response Schema (AiAgentAccessRequestDTO)
FieldTypeDescription
requestIdstringUnique request ID (req_...).
tenantId, agentId, agentNameuuid / stringTenant and target AI agent identifiers.
requestedBystringEmail of requester.
requestedScopes, requestedMcpServers, justificationstring?Requested permissions and rationale.
statusstringPending | Approved | Denied.
reviewedBy, reviewNotes, createdOn, reviewedOnstring? / datetime?Approval metadata and UTC timestamps.
GET /api/ai-agents/certifications | POST /api/ai-agents/certifications/campaign | POST /api/ai-agents/certifications/{certificationId}/complete
Bearer JWT

Identity Governance & Administration (IGA) certification campaigns for AI agents. Launching a campaign creates 14-day review tasks for every non-revoked agent; certifying extends nextCertificationDueOn by 90 days, while revoking immediately triggers the Kill-Switch.

Request Parameters
ParameterIn / EndpointTypeRequiredDescription
campaignNameBody (Campaign)stringOptionalCampaign display name (defaults to current quarter review, e.g. Q4 2026 AI Agent Review).
certificationIdPath (Complete)stringRequiredCertification review ID (crt_...).
decisionBody (Complete)stringRequiredCertified (renews access for 90 days) or Revoked (immediately revokes agent).
notesBody (Complete)stringOptionalCompliance audit notes.
Response Schema (AiAgentCertificationDTO)
FieldTypeDescription
certificationIdstringUnique review ID (crt_...).
tenantId, campaignName, agentId, agentNameuuid / stringCampaign and reviewed agent metadata.
reviewerEmailstring?Assigned human reviewer (defaults to agent's ownerEmail).
statusstringPending | Certified | Revoked.
notes, dueDate, createdOn, completedOnstring? / datetime?Review notes and UTC schedule/completion timestamps.
GET /api/ai-agents/audit-logs
Bearer JWT

Retrieves the immutable AI Agent governance telemetry stream (registrations, policy updates, Shadow AI scans, JIT token issuances, HITL approvals, certifications, and Kill-Switch revocations).

Request Parameters
ParameterInTypeRequiredDescription
agentIdQuerystringOptionalFilter telemetry events to a specific AI agent ID.
limitQueryintegerOptionalMax records to return (1–500, default: 100).
Response Schema (AiAgentAuditLogDTO[])
FieldTypeDescription
logIdstringUnique log entry ID (log_...).
tenantId, agentId, agentNameuuid / string?Tenant and agent context (null for tenant-wide scans/campaigns).
actionstringEvent code: AgentRegistered, AgentPolicyUpdated, JitTokenIssued, ShadowAiDiscoveryScan, AccessRequestCreated, AccessRequestApproved, AccessRequestDenied, CertificationCampaignStarted, AgentCertified, KillSwitchRevoked, AgentReactivated, AgentDecommissioned.
actorstringEmail or user ID of the admin/system that triggered the action.
severitystringinfo | warning | critical.
detailsstringHuman-readable audit description including scopes, TTL, and reason.
createdOndatetimeUTC timestamp of the audit event.
cURL Example Register an AI Agent & Mint a Short-Lived JIT Token
# 1. Register a Governed AI Agent Identity
curl -X POST "https://<your-tenant-domain>/api/ai-agents" \
  -H "Authorization: Bearer <ADMIN_ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support Triage Copilot",
    "agentType": "Copilot",
    "modelProvider": "Anthropic",
    "ownerEmail": "[email protected]",
    "ownerName": "Jane Doe",
    "delegationMode": "OnBehalfOfUser",
    "allowedScopes": "users:read, tickets:read",
    "allowedMcpServers": "mcp://zendesk-readonly",
    "allowedApiEndpoints": "/api/users",
    "maxTokenTtlMinutes": 15,
    "requireHumanApprovalForWrite": true
  }'

# 2. Issue a Short-Lived JIT Scoped Token for the Agent
curl -X POST "https://<your-tenant-domain>/api/ai-agents/<AGENT_ID>/issue-jit-token" \
  -H "Authorization: Bearer <ADMIN_ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "requestedScopes": "users:read", "ttlMinutes": 10, "targetMcpServer": "mcp://zendesk-readonly" }'

# 3. Emergency Kill-Switch (Instant Revocation)
curl -X POST "https://<your-tenant-domain>/api/ai-agents/<AGENT_ID>/revoke" \
  -H "Authorization: Bearer <ADMIN_ACCESS_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{ "reason": "Anomalous API burst detected", "suspendOnly": false }'
Need the full HTTP endpoint catalog? Explore the complete REST & Protocol API Reference for every endpoint in Auth.SSO.Id and Core.SSO.Id, or dive into the component stories in the left sidebar.