# Client credentials

> A back-end service gets a token for itself, with no user and no browser involved, and presents it to the API it calls.

A service proves who it is to the realm and gets an access token about itself. No user signs in and no browser is
involved: the service presents the token to the API it calls, and the API sees which service is calling and what it
may do.

Use it for service-to-service calls: a nightly job, a back end calling another back end, a webhook handler. Never use
it in a browser or a mobile app, because the service must keep a secret or a private key. For access on a user's
behalf, use the [browser sign-in](../../single-sign-on/authorization-code/) or [token exchange](../token-exchange/). An
[agent's](../../../agents/ai-agents/) client uses this same grant, and its token is then about the agent.

## Before you begin

- **Who can do it:** a realm administrator (a group holding `RealmOwner`) registers the service; `RealmViewer` can
  see it but not change it. The service then asks for its own tokens.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** the service can keep a secret or a private key, and you know the API it calls.

## How it works

The service asks the token endpoint, proving who it is ([client authentication](../../client-security/client-authentication/)) and
naming the API it will call:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -u orders-sync:s6BhdRkqt3 \
  -d grant_type=client_credentials \
  -d scope=orders.read \
  --data-urlencode resource=https://orders.example.com/api
```

```json
{
  "access_token": "eyJhbGciOiJFUzI1NiIs…",
  "token_type": "Bearer",
  "expires_in": 300
}
```

`scope` is in the answer only when it differs from what was asked, such as when nothing was asked and the client's
defaults were granted. The [access token's](../access-tokens/) claims:

```json
{
  "iss": "https://foobar.cvyuh.com/oauth2",
  "sub": "orders-sync",
  "aud": "https://orders.example.com/api",
  "exp": <iat + 300>,
  "iat": <unix time>,
  "jti": "b1f7c0d2-5e3a-4a8f-9c61-2d4e7f8a9b10",
  "client_id": "orders-sync",
  "principal_type": "oauth2Client",
  "scope": "orders.read"
}
```

| Claim | What it says |
|---|---|
| `sub`, `client_id` | The client, because the token is about the client |
| `aud` | The API it is for ([resource indicators](../resource-indicators/)) |
| `scope` | What it allows |
| `principal_type` | That it names a client, so an API never mistakes it for a user |

There is no refresh token and no ID token: the service asks again when the token expires.

## Set it up

Register the service with
`POST https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client?id=orders-sync` (see [Call the API](../../../../develop/api/)), setting the fields below; realm settings are changed with
`PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`.

| Where | Setting | What it does |
|---|---|---|
| Client | `grantTypes` includes `client_credentials` | The default for a new client |
| Client | `tokenEndpointAuthMethod` and its secret or key | How the service proves who it is ([client authentication](../../client-security/client-authentication/)) |
| Client | `scopes`, `defaultScopes` | What it may ask for, and what it gets when it asks for nothing |
| Client | `allowedResources`, `defaultAudience` | The APIs its tokens may be for, and the one used when the request names none |
| Realm | `grantTypes` includes `client_credentials` | On by default |
| Realm | `requireResource` | Every request must name its API (default off) |
| Realm | `accessTokenLifetimeSecs` | How long access tokens live (default 300) |

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `client_credentials` in a new client's `grantTypes` | yes | per client |
| `requireResource` | off | on or off |
| `accessTokenLifetimeSecs` | 300 | 1 to 86,400; an agent's token may be capped lower by its risk class |
| Refresh tokens | none for this grant | fixed |

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| `invalid_scope` | The scope isn't held by both the client and the realm, or it's `openid` | Add the scope to both lists; drop `openid` |
| `invalid_target` | No `resource` and no `defaultAudience`, or `requireResource` is on | Send `resource`, or set `defaultAudience` |
| `unauthorized_client` | The client is public (`none`) | Give it a secret or a key |
| A new token on every call | The service doesn't keep its token until it expires | Cache the token, and ask again shortly before `expires_in` |

## Audit record

Each request is one `TOKEN_ISSUED` record with `grantType` `client_credentials`, under the client (or the agent, for
an agent's client), issued or refused with its `error`. See them in **Audit → Authentication**.

## Good to know

- **Scopes must be held by both the client and the realm.** Any other is refused `invalid_scope`. With none asked,
  the client's defaults the realm holds are granted. `openid` is refused: no user signed in.
- **Every token names an API.** A request that names no `resource` gets the client's `defaultAudience`. A client
  with no `defaultAudience` must name one, and so must every request when the realm sets `requireResource`.
  Otherwise the request is refused `invalid_target`.
- **Structured permissions are allowed.** A request may carry `authorization_details`, of the types the client may
  ask for ([rich authorization requests](../../../authorization/rich-authorization-requests/)).
- **A public client can never use this grant.** It's refused `unauthorized_client`.
- **For an agent's client, the realm's [agent guardrails](../../../../gateway/guardrails/agent-guardrails/) apply.**
  A scope a guardrail holds for the business owner's approval is refused `interaction_required`, or waits for the
  owner when the request asks to
  ([the request waits for the owner](../../../../gateway/guardrails/agent-guardrails/#or-the-request-waits-for-the-owner)).
  The token lives no longer than the agent's risk class allows.

## Reference

### Errors

| Error | When |
|---|---|
| `invalid_client` (401) | The client didn't prove who it is |
| `unauthorized_client` | The client is public, or may not use this grant |
| `invalid_scope` | A scope the client or the realm doesn't hold, or `openid` |
| `invalid_target` | A `resource` the client may not name; or none, with no default or under `requireResource` |
| `interaction_required` | An agent's client asked for a scope its owner must approve first |

## Related

- [Let one service call another](../../../guides/services/service-to-service/): the task, start to finish.
- [Choose how a client proves itself](../../../guides/services/choose-client-authentication/):
  secrets, signed assertions and more.
- [Set how long tokens live](../../../guides/services/set-token-lifetimes/): lifetimes per realm.
- [Client authentication](../../client-security/client-authentication/): every way a client proves who it is.
- [Access tokens](../access-tokens/): what every access token carries.
