> ## Documentation Index
> Fetch the complete documentation index at: https://developers.authlete.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> ### Authlete versions
> Authlete 3.0 is the current version. Unless the user says they use another version, answer for Authlete 3.0 using the 3.x documentation.
> Documentation for Authlete 2.x (pages under `/v2/` and `/ja/v2/`) is for the legacy version. Refer to it only when the user is on Authlete 2.x.
>
> ### Authlete architecture
> Authlete is a backend engine for OAuth 2.0 and OpenID Connect processing. End users and client applications do not call it directly; the service provider's authorization server and API server call Authlete's APIs. Authlete handles protocol processing and token, client, and service management, while the service provider owns the OAuth/OIDC endpoints and user authentication.
> See [Architecture](https://developers.authlete.com/get-started/introduction-to-authlete/architecture.md).
>
> ### Concepts
> If the user is new to Authlete, read these pages first:
> - [Request and Response](https://developers.authlete.com/get-started/concepts/request-and-response.md): Core API requests pass the client's request parameters as-is, and responses return `resultCode`, `action`, and `responseContent`.
> - [Action Handling](https://developers.authlete.com/get-started/concepts/action-handling.md): Branch on `action`, never on `resultCode`, and map each action to the HTTP response your server returns.
> - [Two-Step API Calls](https://developers.authlete.com/get-started/concepts/two-step-api-calls.md): Actions such as `INTERACTION` are completed with a second call (`/auth/authorization/issue` or `/auth/authorization/fail`) linked by a `ticket`.
> - [Management API Overview](https://developers.authlete.com/get-started/concepts/overview.md): The Management API configures services, manages clients, and operates issued tokens, separately from the protocol flows handled by the Core API.
> - [API Authentication](https://developers.authlete.com/get-started/concepts/authentication.md): Authlete APIs use bearer tokens: a Service Access Token (one service) or an Organization Token (the whole organization).

# Implementing Poppy with Authlete

> Make your Company work with Personal Agents under the Personal Agent Protocol (Poppy), with Authlete as your authorization server.

A Poppy Company publishes discovery files, signs Users in on its own pages, and checks two things on every request: the `Poppy-Session` header and, once the User has signed in, the access token.

Authlete handles the OAuth parts for you. It recognizes Personal Agents by their URL (CIMD), verifies their signed client assertions (`private_key_jwt`), binds tokens to their keys (DPoP), and issues and checks tokens. Your servers make the same Authlete API calls as for any other client.

This guide sets up an Authlete service for Poppy and walks through each piece a Company builds, one Authlete API call per step. It uses Stays, Authlete's reference Company, as the example. For what Poppy is and how to test your Company, see the [Poppy overview](https://developers.authlete.com/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md).

## When to use Poppy

* **Customers bring their own agents.** Personal agents such as Meta's Muse look for Poppy on the sites they visit. With Poppy, those agents can sign your customers in and act for them, within limits you set.
* **You want one way in for every agent.** Instead of a separate integration for each agent, you publish one `poppy.json` file and any Poppy agent can work with you.
* **You already use Authlete.** Poppy's sign-in is OAuth. Your Authlete service handles it with a few setting changes.

## How the flow works

1. The agent reads your `poppy.json` and your OAuth metadata, and finds your authorization server.
2. The agent sends an authorization request with its URL as `client_id`. Authlete fetches the agent's metadata and registers it.
3. The User signs in on your page and approves the scopes, and your server issues an authorization code.
4. The agent exchanges the code for an access token, proving its identity with a signed assertion and, optionally, a DPoP proof.
5. Your API checks the `Poppy-Session` header and the access token on every request.

Discoverypoppy.json and metadata

Agent identityThe client ID is a URL

Sign-inThe User approves scopes

Access tokenBound to the agent's key

API callSession header and token

## Prerequisites

* An Authlete 3.0.40 or later service and its **Service Access Token**. To create them, follow [First API Call](https://developers.authlete.com/get-started/quickstarts/getting-started.md). Use a test service: you will change its settings.
* Two HTTPS hosts: your Company's domain, such as `stays.poppysandbox.dev`, and your authorization server, such as `auth.stays.poppysandbox.dev`.
* To run the cURL commands: `curl`, `jq`, and `openssl`.

In the commands below, replace `SERVICE_ID` and `SERVICE_ACCESS_TOKEN` with your values, and `us.authlete.com` with your service's cluster.

### Set up the SDK

To follow the TypeScript, Go, or Ruby tabs, install the SDK and create a client. The steps reuse this client.

> [tab] TypeScript
>
> ```bash wrap theme={null}
> npm add @authlete/typescript-sdk
> ```
>
> ```typescript wrap theme={null}
> import { Authlete } from "@authlete/typescript-sdk";
>
> const authlete = new Authlete({
>   serverURL: "https://us.authlete.com",
>   bearer: "SERVICE_ACCESS_TOKEN",
> });
> const serviceId = "SERVICE_ID";
> // Each call returns { headers, result }; the steps use `result`.
> ```

> [tab] Go
>
> ```bash wrap theme={null}
> go get github.com/authlete/authlete-go-sdk
> ```
>
> ```go wrap theme={null}
> import (
> 	"context"
> 	"log"
>
> 	authlete "github.com/authlete/authlete-go-sdk"
> 	"github.com/authlete/authlete-go-sdk/models/components"
> 	"github.com/authlete/authlete-go-sdk/models/operations"
> )
>
> ctx := context.Background()
> s := authlete.New(
> 	authlete.WithServerURL("https://us.authlete.com"),
> 	authlete.WithServiceID("SERVICE_ID"),
> 	authlete.WithSecurity("SERVICE_ACCESS_TOKEN"),
> )
> ```

> [tab] Ruby
>
> ```bash wrap theme={null}
> gem install authlete_ruby_sdk
> ```
>
> ```ruby wrap theme={null}
> require "authlete_ruby_sdk"
>
> Models = ::Authlete::Models
> authlete = ::Authlete::Client.new(
>   bearer:     "SERVICE_ACCESS_TOKEN",
>   server_url: "https://us.authlete.com"
> )
> SERVICE_ID = "SERVICE_ID"
> ```

### Get an agent ID

A Personal Agent's client ID is the URL of its metadata document. This guide uses the [Poppy Agent Playground](https://poppy-playground.authlete.app), a public test agent. Open its URL to see the document Authlete will fetch:

```sh wrap theme={null}
curl -s https://poppy-playground.authlete.app/agent.json
```

```json wrap theme={null}
{
  "client_id": "https://poppy-playground.authlete.app/agent.json",
  "client_name": "Poppy Agent Playground",
  "jwks_uri": "https://poppy-playground.authlete.app/jwks.json",
  "redirect_uris": ["https://poppy-playground.authlete.app/callback"],
  "token_endpoint_auth_method": "private_key_jwt",
  "grant_types": [
    "authorization_code",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code"
  ],
  "response_types": ["code"]
}
```

Unlike most CIMD clients, a Personal Agent is not a public client. It publishes its keys at `jwks_uri` and signs a client assertion with them (`private_key_jwt`). This agent doesn't name its signing algorithm (`token_endpoint_auth_signing_alg`), and Poppy doesn't require it. Authlete accepts its assertion when it verifies with one of the agent's published keys. It also lists the device grant, which you handle with a metadata policy below.

### Configure the service

Set the following in **Service Settings** in the console, or with the [Update Service API](https://developers.authlete.com/api-reference/service-management/update-service.md). The API replaces the whole service, so read the service first and send it back with these fields changed.

| Setting | Value | Why |
| :- | :- | :- |
| `clientIdMetadataDocumentSupported` | `true` | Accepts a URL as `client_id`. |
| `cimdAllowlistEnabled`, `cimdAllowlist` | `true`, `https://poppy-playground.authlete.app/agent.json` | Accepts only the test agent while you build. See [Before you go live](#before-you-go-live). |
| `supportedTokenAuthMethods` | includes `PRIVATE_KEY_JWT` | Personal Agents authenticate with signed assertions. Without it: `[A505306]`. |
| `clientAssertionAudRestrictedToIssuer` | `true` | Rejects a client assertion whose `aud` isn't your issuer, as Poppy requires. It's off by default, and without it an assertion addressed to your token endpoint is accepted. Rejected assertions fail with `[A157356]`. |
| `supportedGrantTypes` | `AUTHORIZATION_CODE`, `REFRESH_TOKEN` | Direct Sign-In and the refresh tokens Poppy requires. |
| `cimdMetadataPolicyEnabled`, `cimdMetadataPolicy` | `true`, a policy that removes grant types you don't offer | The service must support every grant type an agent's metadata lists, or the request fails with `[A505307]`. The Playground lists the device grant, so drop it with a [metadata policy](https://developers.authlete.com/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md#metadata-policy). |
| `pkceRequired`, `pkceS256Required` | `true` | Direct Sign-In uses PKCE with `S256`. |
| `supportedScopes` | Your scopes, such as `stays:read` and `stays:write` | The scopes your `poppy.json` describes. |
| `protectedResources` | Your Company's URL, such as `https://stays.poppysandbox.dev` | Poppy requires the authorization server metadata to list your Company in `protected_resources`. In the console, it is **Protected Resources** under **Metadata**. |
| `accessTokenDuration` | `3600` | The default `0` issues tokens that are already expired. |
| `issuer`, `authorizationEndpoint`, `tokenEndpoint` | Your authorization server's URLs | Agents find your endpoints in the metadata. Set the revocation endpoint too: Poppy requires it. |

Don't add `DEVICE_CODE` just because an agent lists it. Listing it in your metadata tells agents you offer Device Sign-In, which also needs a device authorization endpoint and a verification page (`deviceVerificationUri`). Add it only when you build Device Sign-In; otherwise every attempt fails with `[A222101]`.

To support Pushed Authorization Requests (PAR), which Poppy agents should use when your metadata lists the endpoint, add a `POST /oauth/par` endpoint that forwards the request to Authlete's `/pushed_auth_req` API, and set its URL in the service. The rest of this guide works the same with or without PAR.

## What you build

A Company has two hosts. Each endpoint on the authorization server is a thin wrapper around one Authlete API call.

| Host | Your endpoint | Authlete API | Step |
| :- | :- | :- | :- |
| Company domain | `GET /.well-known/poppy.json` | None | 1 |
| Company domain | `GET /.well-known/oauth-protected-resource` | None | 2 |
| Authorization server | `GET /.well-known/oauth-authorization-server` | `GET /api/{serviceId}/service/configuration` | 3 |
| Authorization server | `GET /oauth/authorize` | `POST /api/{serviceId}/auth/authorization` | 4 |
| Authorization server | Sign-in and consent page | `POST /api/{serviceId}/auth/authorization/issue` or `/fail` | 5 |
| Authorization server | `POST /oauth/token` | `POST /api/{serviceId}/auth/token` | 6 |
| Company domain | Your API | `POST /api/{serviceId}/auth/introspection` | 7 |
| Authorization server | `POST /oauth/revoke` | `POST /api/{serviceId}/auth/revocation` | 8 |

## Endpoints you'll use

| Step | Authlete API | What it does | Reference |
| :- | :- | :- | :- |
| 3 | `GET /api/{serviceId}/service/configuration` | Returns the authorization server metadata | [Get Service Configuration](https://developers.authlete.com/api-reference/service-management/get-service-configuration.md) |
| 4 | `POST /api/{serviceId}/auth/authorization` | Processes the authorization request and fetches the agent's metadata | [Process Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/process-authorization-request.md) |
| 5 | `POST /api/{serviceId}/auth/authorization/issue` | Issues the authorization code after approval | [Issue Authorization Response](https://developers.authlete.com/api-reference/authorization-endpoint/issue-authorization-response.md) |
| 6 | `POST /api/{serviceId}/auth/token` | Verifies the agent's assertion and DPoP proof, and issues tokens | [Process Token Request](https://developers.authlete.com/api-reference/token-endpoint/process-token-request.md) |
| 7 | `POST /api/{serviceId}/auth/introspection` | Checks the access token and its DPoP proof | [Process Introspection Request](https://developers.authlete.com/api-reference/introspection-endpoint/process-introspection-request.md) |
| 8 | `POST /api/{serviceId}/auth/revocation` | Revokes tokens when the User signs out | [Process Revocation Request](https://developers.authlete.com/api-reference/revocation-endpoint/process-revocation-request.md) |

## Build it

### 1. Publish poppy.json

Every agent starts at `https://{your domain}/.well-known/poppy.json`. Serve it from your Company's own domain, over HTTPS, with no sign-in. It names your Company and authorization server, describes each scope in the words Users will see, and lists your APIs.

This is Stays' file, abridged:

```json poppy.json wrap theme={null}
{
  "protocol_version": "1.0",
  "organization": { "name": "Stays", "domain": "stays.poppysandbox.dev" },
  "auth": {
    "issuer": "https://auth.stays.poppysandbox.dev",
    "scopes": {
      "stays:read": "See your Stays bookings.",
      "stays:write": "Book a room on your account. Each booking needs your approval."
    },
    "scope_hints": {
      "stays:read": { "changes": "none", "personal_data": true },
      "stays:write": { "changes": "irreversible", "personal_data": true }
    }
  },
  "apis": [
    { "type": "openapi", "url": "https://stays.poppysandbox.dev/openapi.json", "description": "Stays API" }
  ]
}
```

* `organization.domain` must equal the host that serves the file.
* `auth.issuer` must equal the `issuer` in your Authlete service.
* Hints are optional. Each hint you include needs both `changes` (`none`, `reversible`, or `irreversible`) and `personal_data`.
* If you also serve older versions, list only those in `supported_versions`, not your own `protocol_version`.

```sh wrap theme={null}
curl -s https://stays.poppysandbox.dev/.well-known/poppy.json | jq '.organization, .auth.issuer'
```

> [!TIP]
>
> The file loads over HTTPS, and `organization.domain` matches the host.

### 2. Publish the protected resource metadata

Agents check the issuer in `poppy.json` against your protected resource metadata ([RFC 9728](https://www.rfc-editor.org/rfc/rfc9728.html)). Serve it on your Company's domain, next to `poppy.json`. In Poppy, the protected resource is your whole domain, so the file sits at the root with no path after it.

```json /.well-known/oauth-protected-resource wrap theme={null}
{
  "resource": "https://stays.poppysandbox.dev",
  "authorization_servers": ["https://auth.stays.poppysandbox.dev"]
}
```

`resource` must be exactly `https://` followed by your domain.

```sh wrap theme={null}
curl -s https://stays.poppysandbox.dev/.well-known/oauth-protected-resource
```

> [!TIP]
>
> `authorization_servers` contains your Authlete service's `issuer`.

### 3. Serve the authorization server metadata

Next, the agent reads `/.well-known/oauth-authorization-server` on your authorization server. Your server does not build this document. It returns what Authlete generates from your service settings.

Poppy also requires `protected_resources` to list your Company, which completes the two-way check. Authlete includes it when you set `protectedResources` in [Configure the service](#configure-the-service).

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/service/configuration \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN"
```

```typescript TypeScript wrap theme={null}
const { result: config } = await authlete.service.getConfiguration({ serviceId });
// Return `config` as the JSON body of /.well-known/oauth-authorization-server.
```

```go Go wrap theme={null}
config, err := s.Service.GetConfiguration(ctx, operations.ServiceConfigurationAPIRequest{})
if err != nil {
	log.Fatal(err)
}
// Return config.Object as the JSON body of /.well-known/oauth-authorization-server.
```

```ruby Ruby wrap theme={null}
config = authlete.services.configuration(service_id: SERVICE_ID).object
# Return `config` as the JSON body of /.well-known/oauth-authorization-server.
```

```json wrap theme={null}
{
  "issuer": "https://auth.stays.poppysandbox.dev",
  "authorization_endpoint": "https://auth.stays.poppysandbox.dev/oauth/authorize",
  "token_endpoint": "https://auth.stays.poppysandbox.dev/oauth/token",
  "revocation_endpoint": "https://auth.stays.poppysandbox.dev/oauth/revoke",
  "grant_types_supported": ["authorization_code", "refresh_token"],
  "token_endpoint_auth_methods_supported": ["private_key_jwt"],
  "client_id_metadata_document_supported": true,
  "protected_resources": ["https://stays.poppysandbox.dev"]
}
```

> [!TIP]
>
> `issuer` matches `poppy.json`, `client_id_metadata_document_supported` is `true`, `grant_types_supported` includes `refresh_token`, and `protected_resources` includes your domain.

API reference: [Get Service Configuration](https://developers.authlete.com/api-reference/service-management/get-service-configuration.md)

### 4. Process the authorization request

When a task needs an account, the agent sends the User's browser to your authorization endpoint. Poppy calls this Direct Sign-In. The request carries the agent's URL as `client_id`, the scopes it wants, a PKCE challenge, and `prompt=consent`, which Poppy requires so the User approves the agent every time. If the agent pushed the request first (PAR), the query string carries only `client_id` and `request_uri`. Either way, your server passes the query string to Authlete unchanged.

Authlete sees a URL it does not know, so it fetches the agent's document, checks it, registers the agent, and then checks the rest of the request.

To try it, create a PKCE pair as the agent would:

```sh wrap theme={null}
VERIFIER=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=')
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')
```

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/authorization \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"parameters": "response_type=code&client_id=https%3A%2F%2Fpoppy-playground.authlete.app%2Fagent.json&redirect_uri=https%3A%2F%2Fpoppy-playground.authlete.app%2Fcallback&scope=stays%3Aread%20stays%3Awrite&prompt=consent&code_challenge='"$CHALLENGE"'&code_challenge_method=S256&state=xyz"}'
```

```typescript TypeScript wrap theme={null}
// `parameters` is the query string of GET /oauth/authorize, as received.
const { result: r } = await authlete.authorization.processRequest({
  serviceId,
  authorizationRequest: { parameters },
});
// INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with r.responseContent.
```

```go Go wrap theme={null}
// `parameters` is the query string of GET /oauth/authorize, as received.
res, err := s.Authorization.ProcessRequest(ctx, operations.AuthAuthorizationAPIRequest{
	Body: components.AuthorizationRequest{Parameters: parameters},
})
if err != nil {
	log.Fatal(err)
}
r := res.AuthorizationResponse
// INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with *r.ResponseContent.
```

```ruby Ruby wrap theme={null}
# `parameters` is the query string of GET /oauth/authorize, as received.
r = authlete.authorization.process_request(
  service_id: SERVICE_ID,
  authorization_request: Models::Components::AuthorizationRequest.new(parameters: parameters)
).authorization_response
# INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with r.response_content.
```

```json wrap theme={null}
{
  "action": "INTERACTION",
  "ticket": "ArHyOxV-8WF7kEShwwYXpNB3DUb8e14Bw3xFaSSZEBg",
  "metadataDocumentUsed": true,
  "client": {
    "clientName": "Poppy Agent Playground",
    "clientSource": "METADATA_DOCUMENT",
    "metadataDocumentLocation": "https://poppy-playground.authlete.app/agent.json"
  },
  "scopes": [{ "name": "stays:read" }, { "name": "stays:write" }]
}
```

> [!TIP]
>
> `action` is `INTERACTION`, and `client.clientSource` is `METADATA_DOCUMENT`. The agent now appears on the service's **Clients** page.

API reference: [Process Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/process-authorization-request.md)

### 5. Show the consent page and issue the code

`INTERACTION` means the request is valid and it is time to ask the User. Your server signs the User in on your own domain and shows a consent page. Name the agent (`client.clientName`) and show its logo from the `logo_uri` in its metadata, so the User can recognize it. List every scope you will grant, using the descriptions from your `poppy.json`; Poppy requires the consent page to list them all. Stays shows "Book a room on your account. Each booking needs your approval." rather than `stays:write`. Also show the agent's domain and a warning such as "Only continue if you asked this agent to do this just now," and never approve just because the page was opened. Poppy requires these cross-device practices from RFC 10027 (BCP 247), section 2.

When the User approves, send the `ticket` from step 4 and your ID for the User. Authlete returns the redirect URL with the code:

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/authorization/issue \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"ticket": "TICKET", "subject": "demo-user"}'
```

```typescript TypeScript wrap theme={null}
const { result: issued } = await authlete.authorization.issue({
  serviceId,
  authorizationIssueRequest: { ticket: r.ticket!, subject: user.id },
});
// LOCATION: redirect the browser (302) to issued.responseContent.
// If the User declines, call authlete.authorization.fail with reason "DENIED".
```

```go Go wrap theme={null}
res, err := s.Authorization.Issue(ctx, operations.AuthAuthorizationIssueAPIRequest{
	Body: components.AuthorizationIssueRequest{Ticket: *r.Ticket, Subject: userID},
})
if err != nil {
	log.Fatal(err)
}
issued := res.AuthorizationIssueResponse
// LOCATION: redirect the browser (302) to *issued.ResponseContent.
// If the User declines, call s.Authorization.Fail with reason Denied.
```

```ruby Ruby wrap theme={null}
issued = authlete.authorization.issue_response(
  service_id: SERVICE_ID,
  authorization_issue_request: Models::Components::AuthorizationIssueRequest.new(
    ticket: r.ticket, subject: user_id
  )
).authorization_issue_response
# LOCATION: redirect the browser (302) to issued.response_content.
# If the User declines, call authlete.authorization.fail_request with reason DENIED.
```

```json wrap theme={null}
{
  "action": "LOCATION",
  "responseContent": "https://poppy-playground.authlete.app/callback?state=xyz&code=p8UaUBD2o1xkTmqbpTNbl1Av8lUoFaDXQrbE7unaIvM&iss=https%3A%2F%2Fauth.stays.poppysandbox.dev"
}
```

> [!TIP]
>
> `action` is `LOCATION`, and `responseContent` carries a `code` and an `iss` that matches your issuer.

API reference: [Issue Authorization Response](https://developers.authlete.com/api-reference/authorization-endpoint/issue-authorization-response.md) · [Fail Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/fail-authorization-request.md)

### 6. Process the token request

The agent posts the code to your token endpoint. Unlike a public client, it proves who it is with a client assertion: a JWT it signs with one of the keys at its `jwks_uri` (`private_key_jwt`). Poppy requires the assertion's `aud` to be your issuer and its `exp` to be at most 5 minutes after `iat`. It may also send a `DPoP` header, a proof signed with a key it holds, so that the access token is bound to that key.

Your server passes the form body to Authlete unchanged. If the request has a `DPoP` header, also pass it with the HTTP method and the exact public URL of your token endpoint. Authlete checks the code, the PKCE verifier, the assertion against the agent's published keys, and the DPoP proof.

> [!NOTE]
>
> Only the agent holds the keys for the assertion and the DPoP proof, so you can't make this request yourself with cURL. To run it end to end, use the Poppy Agent Playground, as in [Test it](#test-it).

```typescript TypeScript wrap theme={null}
// `parameters` is the form body of POST /oauth/token, as received.
const dpop = req.headers.get("DPoP") ?? undefined;
const { result: t } = await authlete.token.process({
  serviceId,
  tokenRequest: {
    parameters,
    ...(dpop && { dpop, htm: "POST", htu: "https://auth.stays.poppysandbox.dev/oauth/token" }),
  },
});
// If t.dpopNonce is set, return it in a DPoP-Nonce header.
// OK: return 200 with t.responseContent. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

```go Go wrap theme={null}
// `parameters` is the form body of POST /oauth/token, as received.
body := components.TokenRequest{Parameters: parameters}
if d := r.Header.Get("DPoP"); d != "" {
	body.Dpop = &d
	body.Htm = authlete.Pointer("POST")
	body.Htu = authlete.Pointer("https://auth.stays.poppysandbox.dev/oauth/token")
}
res, err := s.Token.Process(ctx, operations.AuthTokenAPIRequest{Body: body})
if err != nil {
	log.Fatal(err)
}
t := res.TokenResponse
// If t.DpopNonce is set, return it in a DPoP-Nonce header.
// OK: return 200 with *t.ResponseContent. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

```ruby Ruby wrap theme={null}
# `parameters` is the form body of POST /oauth/token, as received.
dpop = request.env["HTTP_DPOP"]
t = authlete.tokens.process_request(
  service_id: SERVICE_ID,
  token_request: Models::Components::TokenRequest.new(
    parameters: parameters,
    dpop: dpop,
    htm: (dpop ? "POST" : nil),
    htu: (dpop ? "https://auth.stays.poppysandbox.dev/oauth/token" : nil)
  )
).token_response
# If t.dpop_nonce is set, return it in a DPoP-Nonce header.
# OK: return 200 with t.response_content. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

The form body the agent sends looks like this. Pass it to Authlete as it is:

```text wrap theme={null}
grant_type=authorization_code
&code=p8UaUBD2o1xkTmqbpTNbl1Av8lUoFaDXQrbE7unaIvM
&redirect_uri=https%3A%2F%2Fpoppy-playground.authlete.app%2Fcallback
&client_id=https%3A%2F%2Fpoppy-playground.authlete.app%2Fagent.json
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9...
```

`responseContent` is the JSON your server returns to the agent:

```json wrap theme={null}
{
  "action": "OK",
  "responseContent": "{\"access_token\":\"lhdjpcs1V...\",\"token_type\":\"DPoP\",\"expires_in\":3600,\"scope\":\"stays:read stays:write\",\"refresh_token\":\"bV1jMYeH7cA5...\"}"
}
```

> [!TIP]
>
> `action` is `OK`. `token_type` is `DPoP` when the agent sent a DPoP proof, and `Bearer` otherwise.

API reference: [Process Token Request](https://developers.authlete.com/api-reference/token-endpoint/process-token-request.md)

### 7. Check each request to your API

Every request an agent sends to your API carries a `Poppy-Session` header. Signed-in requests also carry the access token and, for a DPoP-bound token, a fresh DPoP proof. Your API checks the Session header first, then the token.

**The Session header.** Authlete does not check this header; your API does. It is a JWT signed with a short-lived key, and its `poppy_dlg` header holds a delegation that one of the agent's published keys vouches for. Following section 5.3 of the [Poppy specification](https://personalagentprotocol.org/docs/1.0/spec):

1. Check that `Poppy-Version` is `1.0`. If it's missing or a version you don't support, answer `400` with `{"error": "version_unsupported"}`.
2. Verify the delegation with the agent's keys from its `jwks_uri`, then verify the Session header with the key in the delegation's `cnf.jwk`. Reject a Session header without a `poppy_dlg` delegation, including one signed directly with a key from `jwks_uri`. Accept delegations signed with `ES256` or `PS384`. The delegated key can change between requests, so don't treat a new one as an error. When you fetch the agent's metadata and keys, don't connect to loopback, private, or link-local addresses.
3. Check `typ` is `poppy-session+jwt`, `aud` is your issuer, `htm` and `htu` match this request's method and public URL, and `iat` is recent.
4. If the request has an access token, check that `ath` is its hash.
5. Look up the Session by the agent's `client_id`, `sid`, and the User ID in `sub`.

If any check in steps 2 to 5 fails, answer `400` with `{"error": "invalid_session"}`.

**The access token.** Pass the token, the scope this operation needs, and for a DPoP-bound token, the DPoP proof with the method and URL. Authlete checks that the token is valid, carries the scope, and is bound to the key that signed the proof:

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/introspection \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"token": "ACCESS_TOKEN", "scopes": ["stays:write"]}'
```

```typescript TypeScript wrap theme={null}
// From the request: Authorization: DPoP <token>, and the DPoP header.
const { result: i } = await authlete.introspection.process({
  serviceId,
  introspectionRequest: {
    token,
    scopes: ["stays:write"],
    dpop: req.headers.get("DPoP") ?? undefined,
    htm: "POST",
    htu: "https://stays.poppysandbox.dev/stays",
  },
});
// OK: check that i.metadataDocumentLocation equals the Session header's iss (the same agent), then serve the request.
// UNAUTHORIZED: 401. FORBIDDEN: 403.
// On 401 and 403, return i.responseContent in a WWW-Authenticate header.
```

```go Go wrap theme={null}
// From the request: Authorization: DPoP <token>, and the DPoP header.
d := r.Header.Get("DPoP")
res, err := s.Introspection.Process(ctx, operations.AuthIntrospectionAPIRequest{
	Body: components.IntrospectionRequest{
		Token:  token,
		Scopes: []string{"stays:write"},
		Dpop:   &d,
		Htm:    authlete.Pointer("POST"),
		Htu:    authlete.Pointer("https://stays.poppysandbox.dev/stays"),
	},
})
if err != nil {
	log.Fatal(err)
}
i := res.IntrospectionResponse
// OK: check that *i.MetadataDocumentLocation equals the Session header's iss (the same agent), then serve the request.
// UNAUTHORIZED: 401. FORBIDDEN: 403.
// On 401 and 403, return *i.ResponseContent in a WWW-Authenticate header.
```

```ruby Ruby wrap theme={null}
# From the request: Authorization: DPoP <token>, and the DPoP header.
i = authlete.introspection.process_request(
  service_id: SERVICE_ID,
  introspection_request: Models::Components::IntrospectionRequest.new(
    token: token,
    scopes: ["stays:write"],
    dpop: request.env["HTTP_DPOP"],
    htm: "POST",
    htu: "https://stays.poppysandbox.dev/stays"
  )
).introspection_response
# OK: check that i.metadata_document_location equals the Session header's iss (the same agent), then serve the request.
# UNAUTHORIZED: 401. FORBIDDEN: 403.
# On 401 and 403, return i.response_content in a WWW-Authenticate header.
```

```json wrap theme={null}
{
  "action": "OK",
  "subject": "demo-user",
  "scopes": ["stays:read", "stays:write"],
  "metadataDocumentUsed": true,
  "metadataDocumentLocation": "https://poppy-playground.authlete.app/agent.json"
}
```

> [!TIP]
>
> `action` is `OK`, `subject` is the User the agent acts for, and `metadataDocumentLocation` is the agent's URL.

A request with no access token for an operation that needs an account gets `401` with no error code, and the scope it needs in the `WWW-Authenticate` challenge. A token without the scope gets `403` with `insufficient_scope`.

API reference: [Process Introspection Request](https://developers.authlete.com/api-reference/introspection-endpoint/process-introspection-request.md)

### 8. Revoke tokens on sign-out

When the User signs out, the agent revokes every refresh token it holds for your Company at your revocation endpoint. The agent authenticates with a client assertion, as at the token endpoint. Pass the form body to Authlete unchanged:

```typescript TypeScript wrap theme={null}
// `parameters` is the form body of POST /oauth/revoke, as received.
const { result: v } = await authlete.revocation.process({
  serviceId,
  revocationRequest: { parameters },
});
// OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

```go Go wrap theme={null}
// `parameters` is the form body of POST /oauth/revoke, as received.
res, err := s.Revocation.Process(ctx, operations.AuthRevocationAPIRequest{
	Body: components.RevocationRequest{Parameters: parameters},
})
if err != nil {
	log.Fatal(err)
}
v := res.RevocationResponse
// OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

```ruby Ruby wrap theme={null}
# `parameters` is the form body of POST /oauth/revoke, as received.
v = authlete.revocation.process_request(
  service_id: SERVICE_ID,
  revocation_request: Models::Components::RevocationRequest.new(parameters: parameters)
).revocation_response
# OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

> [!TIP]
>
> `action` is `OK`. Authlete also answers `OK` for a token it doesn't know, as RFC 7009 requires.

API reference: [Process Revocation Request](https://developers.authlete.com/api-reference/revocation-endpoint/process-revocation-request.md)

## Test it

Point the [Poppy Agent Playground](https://poppy-playground.authlete.app) at your Company's domain. It runs every step on this page against your servers, signs its client assertion with its own keys, and decodes each request under **Wire**:

1. In the box at the top, enter your domain and click **Discover**. This covers steps 1 to 3.
2. Under **Call an API**, pick an operation that needs an account and click **Send**. Your API should answer `401`, and the agent tells you which scope it needs.
3. Click **Sign in to** your Company, sign in on your page, and approve. This covers steps 4 to 6.
4. Send the same operation again. It should now succeed. This covers step 7.

Then repeat the test with an agent you didn't write, such as the Poppy Simulator. See [See Poppy in action](https://developers.authlete.com/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md#see-poppy-in-action) in the overview, including a checklist of what each tool should find.

## Troubleshoot

| Error | Cause | Fix |
| :- | :- | :- |
| `[A505301]` | Authlete could not fetch the agent's metadata. | The agent's `client_id` URL must be publicly reachable over `https`. |
| `[A505306]` | The service does not support the agent's `token_endpoint_auth_method`. | Add `PRIVATE_KEY_JWT` to `supportedTokenAuthMethods`. |
| `[A505307]` | The service does not support a value in the agent's metadata, usually a grant type. | Drop it with a [metadata policy](https://developers.authlete.com/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md#metadata-policy). Add it to the service only if you offer it. |
| `[A011317]` | The `redirect_uri` is not in the agent's metadata. | The agent must use a redirect URI it lists. |
| `[A157306]` | The agent signed its assertion with an algorithm your service doesn't support, or with a different one from the algorithm its metadata names. | Make sure your service supports `ES256` and `PS384`, which Poppy requires. |
| `[A157356]` | The `aud` claim in the agent's assertion isn't your issuer. | The agent must address its assertion to your issuer, not your token endpoint. Authlete checks this when `clientAssertionAudRestrictedToIssuer` is on. |
| `[A222101]` | Device Sign-In was attempted, but `deviceVerificationUri` is not set. | Set it, or remove `DEVICE_CODE` from `supportedGrantTypes`. |
| `[A057302]` | The access token does not exist. | Return `401`. |
| `[A065308]` | The access token is bound to a DPoP key, but the request has no DPoP proof. | Return `401`. The agent must send a fresh DPoP proof with every request that uses a DPoP-bound token. |
| `[A286301]` | The access token doesn't cover the scope this operation needs. | Return `403` with `insufficient_scope`. The agent can ask the User to sign in again with that scope. |
| `invalid_session` from your API | Your Session header check rejected a valid agent. | Compare `aud` with your issuer, and `htu` with the public URL of the request, not an internal one. |

## Before you go live

* **Decide which agents you accept.** Poppy leaves this to the Company. An [allowlist](https://developers.authlete.com/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md#allowlist) accepts only the agents you list, which is the safest choice but turns away agents you haven't reviewed. Without one, any agent can register, and a [metadata policy](https://developers.authlete.com/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md#metadata-policy) limits what it can declare. Either way, replace the test-only allowlist with your own decision.
* **Sign Users in on your own domain.** Run the authorization server and the sign-in pages on hosts Users recognize, such as `auth.` and `account.` under your domain.
* **Require your issuer as the assertion audience.** Turn on `clientAssertionAudRestrictedToIssuer`, so Authlete rejects client assertions addressed to anything else.
* **Advertise only what works.** Every grant type in your metadata must work, and every scope in `poppy.json` must have a description. Hints are optional, but each one must have both `changes` and `personal_data`.
* **Keep the cache on and development switches off.** Leave `cimdAlwaysRetrieved`, `cimdHttpPermitted`, and `cimdQueryPermitted` off, and turn on `httpAliasProhibited`.
* **Check the Session header on every request**, including signed-out ones.

> [!NOTE]
>
> **Known limitation (§4.1):** Poppy §4.1 requires each `redirect_uris` entry to be on the same domain as `client_id` (or loopback), a rule the spec files under "stricter than OAuth." Since Authlete fetches and validates the CIMD, it does RFC 9700 exact-match on `redirect_uri` but not the §4.1 same-domain check, so a CIMD with `client_id` and `redirect_uris` on different domains is accepted today, though a fully conformant Company would reject it. Authlete will consider adding this check as part of introducing a "Poppy profile."

## Next steps

* [Poppy overview](https://developers.authlete.com/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md): what Poppy is, what Authlete handles, and how to test your Company.
* [CIMD overview](https://developers.authlete.com/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md): every CIMD setting, including the allowlist and metadata policy.
* [Personal Agent Protocol specification](https://personalagentprotocol.org/docs/1.0/spec)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.