# OAuth

> Mint a scoped API key from an existing key with PKCE, or authorize a browser-less device.


# OAuth

:::note
For the OpenRouter-style flow where a user approves your app on `https://anyrouter.dev/auth` and you receive their key (no existing key needed), see the [OAuth PKCE guide](/guides/oauth-pkce). Its code exchange is a public `POST /api/v1/auth/keys` with `{ code, code_verifier, code_challenge_method }`, returning `{ key, user_id }`.
:::

This page covers minting a key via PKCE and the device authorization grant, both for an AnyRouter account you control. To let other users sign in and bill their own credits, use [Sign in with AnyRouter](/guides/sign-in-with-anyrouter).

## Mint a key via PKCE

Lets a trusted local tool that already holds one of your keys (for example a CLI or a dev server on `localhost:3000`) generate a new scoped key. Create an authorization code, then exchange it. This is not an anonymous sign-in flow: creating the code needs an existing `sk-ar-…` key.

::endpoint{method="POST" path="/api/v1/auth/keys/code"}

:::note
Creating the code needs an **LLM API key** (`sk-ar-…`) as the Bearer token. The exchange needs no key; the `code_verifier` proves it is you. The new key is created in your personal workspace.
:::

## The flow

::::steps

:::step{title="Create an authorization code"}
`POST /api/v1/auth/keys/code` with the PKCE challenge and callback details.

| Field | Type | Required | Description |
|---|---|---|---|
| `callback_url` | string | Yes | Any `https` URL, or `http` on `localhost`, `127.0.0.1` or `[::1]` on any port. |
| `code_challenge` | string | Yes | PKCE challenge. |
| `code_challenge_method` | `S256` \| `plain` | No | Defaults to `S256`. `plain` is accepted. |
| `expires_at` | string \| null | No | Expiration of the **new key** (future ISO 8601 timestamp). The authorization code itself always expires after 10 minutes. |
| `key_label` | string | No | Label for the eventual generated key. |
| `limit` | number | No | Credit cap for the key. |
| `usage_limit_type` | `daily` \| `weekly` \| `monthly` | No | Reset interval for `limit`. |

The response returns the authorization code id:

```json
{
  "data": {
    "id": "authcode_123",
    "app_id": 1,
    "created_at": "2026-04-24T00:00:00.000Z"
  }
}
```
:::

:::step{title="Exchange the code for a key"}
`POST /api/v1/auth/keys` with the code and the PKCE verifier. No `Authorization` header is needed.

| Field | Type | Required | Description |
|---|---|---|---|
| `code` | string | Yes | Authorization code id from step 1. |
| `code_verifier` | string | Yes | PKCE verifier (43-128 characters). |
| `code_challenge_method` | `S256` \| `plain` | No | Must match step 1 when sent. |

The response returns the plaintext key **once**:

```json
{
  "key": "sk-ar-v1-actual-secret-only-shown-once",
  "user_id": "user_123"
}
```
:::

::::

## Examples

::::tabs

:::tab{label="1. Create code"}
```bash
curl https://anyrouter.dev/api/v1/auth/keys/code \
  -X POST \
  -H "Authorization: Bearer sk-ar-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "callback_url": "https://example.com:443/callback",
    "code_challenge": "pkce_challenge_value",
    "code_challenge_method": "S256",
    "key_label": "oauth-app",
    "limit": 25,
    "usage_limit_type": "monthly"
  }'
```
:::

:::tab{label="2. Exchange code"}
```bash
curl https://anyrouter.dev/api/v1/auth/keys \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "authcode_123",
    "code_verifier": "pkce_verifier_value",
    "code_challenge_method": "S256"
  }'
```
:::

::::

:::warning
`callback_url` must be an `https://` URL, or `http://` on `localhost`, `127.0.0.1` or `[::1]` (any port). Authorization codes expire after 10 minutes and are single-use, so exchange them promptly.
:::

## Device authorization

For apps that cannot open a browser (a CLI or headless box), use the device authorization grant ([RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)): show the user a short code, they approve it on any device, and your app polls for the credential. It needs no existing API key.

:::warning
`client_id` is **optional**, but if you send one it must exist. Unregistered apps omit it and pass `client_name`, or register first via [`POST /api/v1/mcp/oauth/register`](/guides/sign-in-with-anyrouter#quickstart). An unknown `client_id` fails with `400 invalid_client`:

```json
{ "error": "invalid_client", "error_description": "Unknown client_id" }
```
:::

::::steps

:::step{title="Request a device code"}
`POST /api/v1/oauth/device/code`. Form-encoded or JSON; every field is optional.

| Field | Type | Description |
|---|---|---|
| `client_name` | string | Name shown to the user on the approval screen. Ignored if `client_id` is set and resolves — the registered name is shown instead. |
| `client_id` | string | Optional. **Must be a `client_id` returned by `POST /api/v1/mcp/oauth/register`** — omit it entirely for an unregistered app; don't invent one. An unrecognized `client_id` returns `400 invalid_client`. |
| `scope` | string | Space-separated permissions to request, e.g. `inference read:credits write:llm-keys`. Unrecognized scope strings are dropped; if none survive, the response is `400 invalid_scope`. Omit to request the full device-flow set; the user can narrow it further at approval. |
| `key_label` | string | Suggested name for the key that gets created. |

```json
{
  "device_code": "8f2a…",
  "user_code": "K4RT-9WPZ",
  "verification_uri": "https://anyrouter.dev/cli/device",
  "verification_uri_complete": "https://anyrouter.dev/cli/device?code=K4RT-9WPZ",
  "expires_in": 600,
  "interval": 5
}
```

Show the user `user_code` and `verification_uri`, or open `verification_uri_complete`, which pre-fills the code.
:::

:::step{title="Poll for the token"}
`POST /api/v1/oauth/token` with `grant_type=urn:ietf:params:oauth:grant-type:device_code`, no more often than `interval` seconds.

While the user hasn't finished, you get a `400` with one of:

| `error` | Meaning |
|---|---|
| `authorization_pending` | Not approved yet. Keep polling. |
| `slow_down` | You polled too fast. Wait at least `interval` seconds. |
| `access_denied` | The user declined. Stop polling. |
| `expired_token` | The code expired or was already used. Start over. |

On approval you get the credential:

```json
{
  "access_token": "sk-ar-v1-actual-secret-only-shown-once",
  "token_type": "Bearer",
  "scope": "inference read:credits",
  "user_id": "user_123"
}
```
:::

::::

::::tabs

:::tab{label="1. Request code"}
```bash
curl https://anyrouter.dev/api/v1/oauth/device/code \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"client_name": "My CLI", "scope": "inference read:credits"}'
```
:::

:::tab{label="2. Poll for token"}
```bash
curl https://anyrouter.dev/api/v1/oauth/token \
  -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
  -d "device_code=8f2a..."
```
:::

::::

:::note
`scope` is a request: the user can approve less, so read `scope` in the response. Users can revoke access from their dashboard.
:::

## Errors

Errors use the standard envelope:

```json
{
  "error": {
    "code": "bad_request",
    "message": "callback_url is required",
    "metadata": {
      "type": "invalid_request_error"
    }
  }
}
```

| Status | Meaning | Fix |
|---|---|---|
| 400 | Missing/invalid field (e.g. `callback_url`) | Send a valid `https` (or loopback `http`) `callback_url` and a PKCE challenge. |
| 400 | `invalid_client` — device-flow `client_id` isn't a registered app | Omit `client_id` (use `client_name` instead), or register first via `POST /api/v1/mcp/oauth/register`. |
| 400 | `invalid_scope` — none of the requested device-flow scopes are recognized | Request valid scopes, e.g. `inference read:credits`, or omit `scope` for the default set. |
| 401 | Invalid or expired bearer key | Send a valid `sk-ar-…` key. |


## Related

- [Authentication](/docs/getting-started/authentication.md)
- [API Keys](/docs/api-reference/keys.md)
- [Sign in with AnyRouter](/docs/guides/sign-in-with-anyrouter.md)
- [OAuth PKCE](/docs/guides/oauth-pkce.md)
