# DPoP

> Bind a client's tokens to a key it holds, so a copied token is useless to anyone without the key.

A normal access token is a **bearer** token: whoever holds it can use it. With DPoP (Demonstrating Proof of
Possession), the client holds a key pair and signs a small **proof** for each request. The realm puts the key's
fingerprint inside the token, and from then on accepts the token only beside a fresh proof by that same key. A copy
of the token alone is worthless.

Use it for public apps (browser and mobile), whose tokens are easiest to steal; their refresh tokens are then bound
to the key as well. Use it for any client calling APIs that check proofs, as the realm's own APIs and the
[gateway](../../../../gateway/) do. The [FAPI 2.0 profile](../security-profiles/)
requires it, and an agent's client is held to that profile unless it names another or attests.

## Before you begin

- **Who can do it:** the client signs its own proofs; no setting is needed for that. A realm administrator (a group
  holding `RealmOwner`) can require proofs of a client or change the realm's DPoP settings; `RealmViewer` can read
  them.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** the client can make a key pair and sign ES256 or RS256 JWTs (see [Make proofs in your client](#make-proofs-in-your-client)).

## How it works

A proof is a JWT whose header carries the public key, sent in the `DPoP` header:

```json
{ "typ": "dpop+jwt", "alg": "ES256", "jwk": { "kty": "EC", "crv": "P-256", "x": "…", "y": "…" } }
```

```json
{
  "jti": "e1j3V_bKic8-LAEB",
  "htm": "POST",
  "htu": "https://foobar.cvyuh.com/oauth2/token",
  "iat": <unix time>,
  "nonce": "eyJ7S_zG.eyJH0-Z.HX4w-7v"
}
```

`htm` and `htu` are the request's method and address. A proof sent to an API also carries `ath`, the hash of the
access token it travels with. The realm writes the key's thumbprint into the token as `cnf.jkt`.

**1. The first token request has no nonce yet**, so the realm answers with one:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -H "DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7Li4ufX0.…" \
  -d grant_type=authorization_code \
  -d code=SplxlOBeZQQYbYS6WxSbIA \
  --data-urlencode redirect_uri=https://notes.example.com/callback \
  -d client_id=notes \
  -d code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
```

```http
HTTP/1.1 400 Bad Request
DPoP-Nonce: eyJ7S_zG.eyJH0-Z.HX4w-7v

{ "error": "use_dpop_nonce", "error_description": "the proof must carry the server's nonce" }
```

**2. The client signs a new proof with the nonce** and sends the request again. The token comes back as
`"token_type": "DPoP"`, with the next nonce in `DPoP-Nonce`. Every answer after that carries the next nonce, so a
client pays the extra round trip once.

**3. The client calls an API** with the token under the `DPoP` scheme, beside a new proof for that call:

```sh
curl https://foobar.cvyuh.com/oauth2/userinfo \
  -H "Authorization: DPoP eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9.…" \
  -H "DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7Li4ufX0.…"
```

### Binding the sign-in too

The [browser sign-in](../../single-sign-on/authorization-code/) can be bound to the key, so a stolen code can't be redeemed with
another key. Either name the key's thumbprint as `dpop_jkt` on the sign-in request or the
[pushed request](../pushed-authorization-requests/), or push the request with a `DPoP` header, whose key then binds
the code.

A code bound this way is redeemed only with a proof from that key. Any other proof, or none, is refused
`invalid_grant`, and the code is spent, so the right key can't redeem it afterwards either. Its tokens are bound to
the key whatever the app's own DPoP setting. A pushed request whose `dpop_jkt` and `DPoP` header name different keys
is refused `invalid_dpop_proof`.

## Set it up

A client that sends a proof gets a bound token with no setting at all. To require it of a client, set
`dpopBoundAccessTokens` on the client (`https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client`; see [Call the API](../../../../develop/api/)). The
realm's settings are changed with `PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`.

| Where | Setting | What it does |
|---|---|---|
| Client | `dpopBoundAccessTokens` | Issue this client only bound tokens. A request without a proof is refused (default off) |
| Realm | `dpopNonceRequired` | Require a realm-issued nonce in proofs at the token endpoint (default on) |
| Realm | `dpopSigningAlgs` | The algorithms a proof may use (default `ES256`, `RS256`; `PS256` may be added) |
| Realm | `dpopProofMaxAgeSecs`, `dpopNonceLifetimeSecs` | How old a proof (60) and a nonce (300) may be |

## Make proofs in your client

Any library that follows RFC 9449 works with the realm. Cvyūh doesn't ship a DPoP client library for your apps today:
the prover built into the platform is the one the [gateway](/gateway/protect-apis/token-swap/) uses to bind the
tokens it swaps for. In your own client, a proof is a few lines with any JWT library. In Python, for example:

```python
from cryptography.hazmat.primitives.asymmetric import ec

key = ec.generate_private_key(ec.SECP256R1())          # keep it for the client's lifetime
public_jwk = json.loads(jwt.algorithms.ECAlgorithm.to_jwk(key.public_key()))

def proof(method, url, nonce=None, access_token=None):
    claims = {"jti": str(uuid.uuid4()), "htm": method, "htu": url, "iat": int(time.time())}
    if nonce:
        claims["nonce"] = nonce                         # from the last DPoP-Nonce header
    if access_token:
        digest = hashlib.sha256(access_token.encode()).digest()
        claims["ath"] = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
    return jwt.encode(claims, key, algorithm="ES256", headers={"typ": "dpop+jwt", "jwk": public_jwk})
```

Send `proof("POST", "https://foobar.cvyuh.com/oauth2/token")` in the `DPoP` header; on `use_dpop_nonce`, sign again
with the nonce from `DPoP-Nonce`. Keep the key for as long as the tokens and refresh tokens bound to it.

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `dpopProofMaxAgeSecs`: how old a proof may be | 60 | 1 to 300, plus the clock skew |
| `dpopNonceRequired`: the realm's nonce in proofs at the token endpoint | on | on or off |
| `dpopNonceLifetimeSecs`: how long a nonce lasts | 300 | 10 to 3,600 |
| `dpopSigningAlgs`: what a proof may be signed with | `ES256`, `RS256` | add `PS256` |
| `dpopBoundAccessTokens`: only bound tokens for this client | off | per client |
| A proof's `iat` with a current nonce | up to a day off | fixed |

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Every first token request answers `use_dpop_nonce` | That's the design: the realm hands out its nonce | Retry once with the nonce from `DPoP-Nonce`, then keep using the latest one |
| `invalid_dpop_proof` at an API | `htu` doesn't match the address called (query strings and fragments are left out), or `ath` is missing | Sign `htu` as the exact scheme, host and path called, with `ath` of the token |
| `invalid_token` at an API | The token was sent as `Bearer` | Send it as `Authorization: DPoP <token>` |
| A refresh fails after the app restarts | The key was lost, and the family is bound to it | Store the key with the refresh token, or sign the user in again |

## Audit record

Each token request is a `TOKEN_ISSUED` record; a bound token's record names the key's thumbprint in its context
(`bound`), and a refused one its `error`. See them in **Audit → Authentication**.

## Good to know

- **A proof works once**, for one request (its method and address), within a minute (`dpopProofMaxAgeSecs`, plus
  the clock skew).
- **One proof per request.** A request with more than one `DPoP` header is refused.
- **The nonce is checked first.** At the token endpoint, the realm asks for a nonce before it authenticates the
  client, so a one-time credential, such as an agent's bootstrap assertion, is never spent on that round trip.
- **A wrong clock is forgiven by the nonce.** A proof whose `iat` is outside the minute, by up to a day either way,
  is taken once it carries a current nonce of the realm's. One without a nonce is asked for one, not refused. This
  holds at the token endpoint and at the realm's own APIs, and at the gateway when it issues nonces.
- **Bound and plain don't mix.** A bound token presented as a plain bearer token is refused, and so is a plain token
  presented under the `DPoP` scheme.
- **Introspection shows the binding**, so an API can check it ([introspection](../../revoke-access/introspection/)).
- **Exchanged tokens are bound too.** A token from [token exchange](../../tokens/token-exchange/) is bound to the exchanging
  client's key.
- **The realm's own APIs check the proof** (userinfo, the policy service), and so does the
  gateway (see [Bound tokens at the gateway](/gateway/protect-apis/bound-tokens/)).
- **One binding per client.** A client is registered for DPoP or for
  [certificate-bound tokens](../certificate-bound-tokens/), never both.

## Reference

### Errors

Where the client gets its tokens (the sign-in, pushed request and token endpoints):

| Error | When |
|---|---|
| `use_dpop_nonce` (400) | The proof has no nonce, or one that is no longer current. Retry with the one in `DPoP-Nonce` |
| `invalid_dpop_proof` (400) | No proof from a client issued only bound tokens; more than one `DPoP` header; a proof that doesn't verify, names another method or address, has an `iat` more than a day off, or was used before; or a pushed request whose `dpop_jkt` names another key |
| `invalid_grant` (400) | A code bound to a key, redeemed with another proof or none |
| `invalid_request` (400) | A `dpop_jkt` that isn't a key's SHA-256 thumbprint |

At the realm's own APIs:

| Error | When |
|---|---|
| `use_dpop_nonce` (401) | A proof outside its time, without a current nonce. The answer carries `WWW-Authenticate: DPoP error="use_dpop_nonce"` and a fresh `DPoP-Nonce` |
| `invalid_dpop_proof` (401) | A bound token without a proof, or with one that doesn't hold: another key, another request, the wrong `ath`, or used before |
| `invalid_token` (401) | A bound token sent as a bearer token, or a plain token sent under `DPoP` |

## Related

- [Bind tokens to a key](../../../guides/services/bind-tokens-to-a-key/): the task, start to
  finish.
- [Hold a client to FAPI 2.0](../../../guides/services/fapi2-clients/): DPoP under the strictest
  profile.
- [Bound tokens at the gateway](/gateway/protect-apis/bound-tokens/): proofs checked in front of your APIs.
- [Certificate-bound tokens](../certificate-bound-tokens/): bind tokens to a TLS certificate instead.
- [Security profiles](../security-profiles/): the profiles that require a bound token.
