# Client authentication

> Each app, service and agent proves who it is to the realm in the one way you registered for it, and guessing is locked out.

Every confidential client proves who it is before the realm gives it a token: with a secret, with an assertion signed
by its own private key, with a TLS certificate, or with an attester's statement. A browser or mobile app, which can't
keep a secret, proves nothing and relies on PKCE instead. You register exactly one method per client, and the realm
accepts that one only.

Pick the method by where the client runs. A server with a secret store can use a secret; a server that can keep a
private key should use `private_key_jwt`, so nothing the realm stores could sign in as it. An agent's client uses
`private_key_jwt` or [attestation](../attestation/), never a secret. Secrets can be rotated with an overlap, so a
planned change never breaks a caller.

## Before you begin

- **Who can do it:** a realm administrator (a group holding `RealmOwner`) sets a client's method, secret and keys;
  `RealmViewer` can read them, never a secret. The client then authenticates itself on each call.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** the client is registered ([Register an app](../../register-an-app/)).

## How it works

The same method is used wherever a client authenticates: the token endpoint, and
[pushed authorization requests](../pushed-authorization-requests/), [introspection](../../revoke-access/introspection/) and
revocation ([Revoke tokens](../../revoke-access/revocation/)).

| Method | What the client presents | For |
|---|---|---|
| `client_secret_basic` | A secret, in the `Authorization` header | Servers with a secret store |
| `client_secret_post` | A secret, in the request body | Servers whose library can't send the header |
| `private_key_jwt` | A short JWT signed with its own private key; the realm holds only the public key | Servers that can keep a key, high-security clients, and agents |
| `self_signed_tls_client_auth` | The TLS certificate it connects with, at the realm host's mtls alias, holding one of its registered keys ([certificate-bound tokens](../certificate-bound-tokens/)) | Servers that hold a TLS certificate. Never an agent's client |
| `attest_jwt_client_auth` | A statement from an attester the realm trusts, and a proof signed by the key it names ([client attestation](../attestation/)) | Agents and apps whose software and instance an attester vouches for |
| `none` | Nothing: it's a public app, and PKCE protects its sign-ins | Browser and mobile apps |

`private_key_jwt` is the strongest of the common ones: the realm never holds anything a thief could use, and each
assertion works once.

### A `private_key_jwt` client signs in

The client signs a short JWT naming itself as both `iss` and `sub`, and the realm's issuer as `aud`, and sends it in
the request:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -d grant_type=client_credentials \
  -d scope=orders.read \
  -d client_id=orders-sync \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6Im9yZGVycy0xIn0.eyJpc3MiOiJvcmRlcnMtc3luYyJ9.…
```

The assertion's claims:

```json
{
  "iss": "orders-sync",
  "sub": "orders-sync",
  "aud": "https://foobar.cvyuh.com/oauth2",
  "jti": "9f2c4d1e-6b8a-4f3e-9c1d-2a7b5e8f0c36",
  "exp": <unix time>
}
```

### Where an agent's key comes from

An agent's `private_key_jwt` client names where its assertion is trusted from, in `assertionTrust`:

- **`registeredKey`:** a key the client registers in `jwks` or `jwksUri`.
- **`amBootstrap`:** the realm itself. A realm administrator mints a one-time assertion with
  `POST https://foobar.cvyuh.com/api/v0/am/clients/v1/<client-id>/bootstrap` (see [Call the API](../../../../develop/api/)) and hands it to the agent for its first token. It's valid for
  `bootstrapAssertionLifetimeSecs` (300 seconds by default).
- **`spiffe`:** the agent's workload platform, as a JWT-SVID. See [workload identity](../../../agents/workload-identity/).

### Rotating a secret with an overlap

Writing a new `clientSecret` on a client rotates it. With the realm's `clientSecretRotationGraceSecs` set, the
replaced secret goes on authenticating beside the new one until the grace ends or the old secret's own expiry,
whichever is first. Only the last secret replaced is kept, and only the realm writes it: a write that names
`previousClientSecret` itself is refused. Each use of the old secret is recorded on the
[audit trail](../../../../audit-reports/audit-trail/), so you can see which callers haven't moved yet.

Rotate with **no grace** (the default) after a leak, so the old secret stops at once. Set a grace for a planned
rotation, long enough for every caller to pick up the new secret.

## Set it up

Set the client's method when you register it with
`POST https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client?id=<client-id>`, or change it on the client later. Set the realm's settings
with `PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`.

| Where | Setting | What it does |
|---|---|---|
| Client | `tokenEndpointAuthMethod` | The one method |
| Client | `clientSecret` | For the two secret methods. Writing a new one rotates it |
| Client | `clientSecretExpiresAt` | When the secret stops working (unset: never) |
| Client | `jwks` or `jwksUri` | The public keys for `private_key_jwt` or `self_signed_tls_client_auth`: one or the other |
| Client | `tokenEndpointAuthSigningAlg` | Pins the assertion's algorithm (`ES256`, `RS256`, `PS256`) |
| Client | `assertionTrust` | For an agent's `private_key_jwt` client: `registeredKey`, `amBootstrap` or `spiffe` |
| Realm | `tokenEndpointAuthMethods` | The methods the realm accepts at all: `none`, both secret methods and `private_key_jwt` by default. `self_signed_tls_client_auth` and `attest_jwt_client_auth` are off until you add them |
| Realm | `tokenEndpointAuthSigningAlgs` | The algorithms an assertion may be signed with (`ES256` and `RS256` by default; `PS256` too if you add it). A `fapi2` client may use only those that are `ES256` or `PS256`, so `ES256` alone by default |
| Realm | `clientAssertionMaxLifetimeSecs`, `clockSkewSecs` | Assertion lifetime (300) and clock tolerance (60) |
| Realm | `agentKeyMaxLifetimeSecs` | The furthest ahead an agent's key may end (7,776,000 seconds, 90 days) |
| Realm | `bootstrapAssertionLifetimeSecs` | How long a minted bootstrap assertion is valid (300) |
| Realm | `clientSecretRotationGraceSecs` | How long a replaced secret still works (0, a hard cut) |

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `clientAssertionMaxLifetimeSecs`: how far ahead an assertion may expire | 300 | 1 to 3,600 |
| `clockSkewSecs`: leeway on an assertion's times | 60 | 0 to 300 |
| `bootstrapAssertionLifetimeSecs`: a bootstrap assertion's life | 300 | 1 to 3,600 |
| `clientSecretRotationGraceSecs`: how long a replaced secret still works | 0, a hard cut | 0 or more |
| `agentKeyMaxLifetimeSecs`: furthest ahead an agent's key may end | 7,776,000 (90 days) | 3,600 to 31,536,000, in `agentSettings` |
| Key types | EC P-256, or RSA of at least 2,048 bits | fixed |
| Secrets kept per client | the current one, and the one it replaced during the grace | fixed |

## Good to know

- **Only the registered method.** A client registered for the header can't send its secret in the body. Presenting
  two methods at once is refused with `invalid_request`.
- **Nothing to learn from a refusal.** An unknown client, an inactive one, a wrong secret and a wrong method all get
  the same `invalid_client`, in the same time.
- **Secret guessing is locked out** by the realm's [lockout](../../../authentication/lockout/) settings, the same ones sign-ins
  use. A locked client is refused even with the right secret, until the lock lapses.
- **An assertion is checked in full.** It must name the client as `iss` and `sub`; name the realm's issuer as `aud`,
  as a single string; carry a `jti` and an `exp`; expire no further ahead than `clientAssertionMaxLifetimeSecs`; and
  be signed with an algorithm the realm accepts, and the client's pinned one if it pins one.
- **Each assertion is accepted once** (replay protection): a `jti` the client has used before is refused.
- **A key can end.** A key whose JWK states an `exp` authenticates nothing once that time has passed. Every key an
  agent's client registers must state one. Rotate by registering the next key beside the old one before it ends.
- **A key is EC P-256 or RSA of at least 2048 bits,** the key in a client's certificate too.
- **Secrets are stored hashed** and never returned. Keep a copy for the app when you set one. A secret past
  `clientSecretExpiresAt` is refused like a wrong one.

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| `invalid_client` with the right secret | The client sends it in the body but is registered for the header, or the other way round | Match `tokenEndpointAuthMethod` to how the library sends it |
| `invalid_client` for a `private_key_jwt` client | `aud` is an array or not the issuer; the assertion lives too long; or the `kid` isn't among its keys | Send `aud` as the string `https://foobar.cvyuh.com/oauth2`, keep `exp` within five minutes, register the key |
| `invalid_client` on the second call with one assertion | Each assertion works once | Sign a new assertion, with a new `jti`, for every request |
| A caller stopped working right after a rotation | The grace is `0`, so the old secret stopped at once | Give the caller the new secret; next time set `clientSecretRotationGraceSecs` first |
| A client is refused even with the right secret | It is locked out after repeated failures | Wait for the lock to lapse, and fix the caller that sent the wrong secret |

## Audit record

- `CLIENT_SECRET_ROTATED`, keyed by the client, when a new secret is written; its context says until when the
  replaced one still holds.
- `CLIENT_SECRET_PREVIOUS_USED`, keyed by the client, each time the replaced secret is used inside the grace: the
  callers that haven't moved yet.
- `TOKEN_ISSUED` with result `FAILED`, keyed by the client it claimed to be, for each refused token request, with its
  `error` and `reason`. A wrong secret also writes `AUTH_FAILURE_RECORDED`, and the lock `ACCOUNT_LOCKED`, keyed `oauth2Client/<client-id>`.

See them in **Audit → Authentication**, or with [What is recorded](/audit-reports/audit-trail/what-is-recorded/).

## Reference

### Errors

| Error | When |
|---|---|
| `invalid_client` (401) | The client is unknown or inactive; the secret, the assertion or the method is wrong; the key has ended; the realm doesn't accept the method; or the client is locked out |
| `invalid_request` (400) | The request presents more than one method, or a `client_id` that disagrees with the one in the `Authorization` header |

## Related

- [Choose how a client proves itself](../../../guides/services/choose-client-authentication/): the
  task, start to finish.
- [Register an agent](../../../guides/agents/register-an-agent/): an agent's client and its keys.
- [Client attestation](../attestation/): prove which software and instance a client is.
- [Certificate-bound tokens](../certificate-bound-tokens/): authenticate with a TLS certificate.
- [Security profiles](../security-profiles/): the methods and algorithms a profile allows.
