# Authorization code with PKCE

> Users sign in to your apps through the browser, and each app gets tokens for them without ever seeing a password.

This is how users sign in to your apps. The app sends the user's browser to the realm, the user signs in on the
realm's own pages, and the browser comes back to the app with a one-time code that the app trades for tokens. The app
never sees the password, and only the app that started the sign-in can redeem the code.

Use it for every app a user signs in to: a web app, a [single-page app](../browser-apps/), a mobile or desktop app.
It is the one browser sign-in the realm offers. For a TV or a command-line tool with no usable browser, use
[device authorization](../device-authorization/); for your own native app with its own sign-in screens, use
[first-party app sign-in](../first-party-apps/). To learn *who* signed in, add [OpenID Connect](../openid-connect/)
on top.

## Before you begin

- **Who can do it:** a realm administrator (a group holding `RealmOwner`) registers the app; `RealmViewer` can see it
  but not change it. Users then sign in themselves.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** know the app's exact return address, and the API its tokens are for.

## How it works

The app proves it started the sign-in with **PKCE**: at the start it makes a random secret, the `code_verifier`, and
sends only its SHA-256 hash, the `code_challenge`. At the end it reveals the verifier. Someone who intercepts the code
can't redeem it without the verifier.

**1. The app sends the browser to the realm:**

```http
GET /oauth2/authorize?response_type=code&client_id=team-wiki
    &redirect_uri=https%3A%2F%2Fwiki.example.com%2Fcallback
    &scope=openid%20profile&resource=https%3A%2F%2Fwiki.example.com%2Fapi
    &state=af0ifjsldkj&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
    &code_challenge_method=S256
Host: foobar.cvyuh.com
```

**2. The user signs in**, and answers the [consent](../../../../customer-identity/consent/) page if they must. The browser then
returns to the app:

```http
HTTP/1.1 303 See Other
Location: https://wiki.example.com/callback?code=eyJhbGciOi…&state=af0ifjsldkj
  &iss=https%3A%2F%2Ffoobar.cvyuh.com%2Foauth2
```

The app checks that `state` is the one it sent, and that `iss` is the realm it expects. Naming the realm in every
answer lets an app that talks to several realms tell which one answered.

**3. The app redeems the code** at the token endpoint, with the verifier. A public app sends only its `client_id`; a
confidential one also proves who it is, as [client authentication](../../client-security/client-authentication/) describes:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -d grant_type=authorization_code \
  -d client_id=team-wiki \
  -d code=eyJhbGciOi… \
  --data-urlencode redirect_uri=https://wiki.example.com/callback \
  -d code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
```

```json
{
  "access_token": "eyJhbGciOiJFUzI1NiIs…",
  "token_type": "Bearer",
  "expires_in": 300,
  "scope": "openid profile",
  "id_token": "eyJhbGciOiJSUzI1NiIs…"
}
```

A [refresh token](../refresh-tokens/) comes too when the realm and the client allow one. The
[access token](../../tokens/access-tokens/) names the API in `resource`; a request that names none gets the client's
`defaultAudience`.

Two more parameters change how the sign-in behaves:

- **`prompt=none`** asks without showing any page. If the user would have to sign in or consent, the app is told so
  (`login_required`, `consent_required`) instead.
- **`login_hint`** tells the sign-in page who the app expects, such as an email address. It is passed on as a hint
  and never trusted: the user still signs in as whoever they are.

## Set it up

These steps use the admin API; [Call the API](../../../../develop/api/) shows how to get a session.

1. Check the realm takes the grant, and offers your API's scopes. `authorization_code` is in the realm's `grantTypes`
   by default. A scope the app asks for must be among the realm's `scopes` as well as the client's, so add your own,
   such as `wiki:read`. Read the settings with `GET https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`, then send the
   existing list with yours added:

   ```sh
   curl -X PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "scopes": ["…existing scopes", "wiki:read"] }'
   ```

   **This list replaces the realm's scopes,** so leave none of the existing ones out.
2. Register the app with `POST https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client?id=team-wiki`, with these fields:

   ```json
   {
     "status": "active",
     "clientName": "Team Wiki",
     "tokenEndpointAuthMethod": "client_secret_basic",
     "clientSecret": "<a long random secret>",
     "grantTypes": ["authorization_code", "refresh_token"],
     "redirectUris": ["https://wiki.example.com/callback"],
     "scopes": ["openid", "profile", "email", "offline_access", "wiki:read"],
     "allowedResources": ["https://wiki.example.com/api"],
     "defaultAudience": "https://wiki.example.com/api"
   }
   ```

   For a public app (a single-page or native app), set `tokenEndpointAuthMethod` to `none` and leave out
   `clientSecret`.
3. Give the app its client ID, its secret if it has one, and the issuer `https://foobar.cvyuh.com/oauth2`. Most libraries
   read the rest from the [discovery document](../../registration/discovery/).

| Where | Setting | What it does |
|---|---|---|
| Client | `grantTypes` includes `authorization_code` | Lets the app use this grant |
| Client | `redirectUris` | The exact addresses the browser may return to |
| Client | `tokenEndpointAuthMethod` | `none` for a public app, or how a confidential app proves itself |
| Client | `allowedResources`, `defaultAudience` | The APIs its tokens may be for, and the one used when the request names none |
| Realm | `grantTypes` includes `authorization_code` | On by default |
| Realm | `authorizationCodeLifetimeSecs` | How long a code lives (default 60) |
| Realm | `consentChallengeLifetimeSecs` | How long the user has to sign in and consent (default 600) |

## What the user sees

1. The app sends the browser to the realm's sign-in page at `https://foobar.cvyuh.com`. A user who is already signed
   in to the realm skips it.
2. The user signs in with the realm's methods: a password, a passkey, an authenticator app, as the realm's
   [sign-in chain](../../../authentication/sign-in-chains/) asks.
3. The first time, the realm shows the consent page: the app's `clientName` and what it asks for. The user allows or
   refuses it ([Consent](/customer-identity/consent/)).
4. The browser returns to the app, which is signed in.

When the realm can't trust the return address, the user sees the realm's own error page instead and stays there:
"the redirect_uri is missing or is not one the client registered".

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `authorizationCodeLifetimeSecs`: how long a code may be redeemed, once | 60 | 1 to 600 |
| `consentChallengeLifetimeSecs`: time to sign in and consent | 600 | 60 to 3,600 |
| PKCE | required, `S256` only | fixed |
| `accessTokenLifetimeSecs` | 300 | 1 to 86,400 |

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| The user sees the realm's error page, and the app hears nothing | The `redirect_uri` isn't exactly one the client registered, or the client may not use this grant | Register the exact address; add `authorization_code` to the client's `grantTypes` |
| `invalid_grant` when the app redeems the code | The code is older than a minute, was used already, or the verifier or `redirect_uri` differs | Redeem at once, once, with the same `redirect_uri` and the matching `code_verifier` |
| `invalid_request` naming `code_challenge` | The app sent no PKCE, or `plain` | Send a `code_challenge` with `code_challenge_method=S256` |
| `invalid_target` | No `resource` and no `defaultAudience` | Set `defaultAudience` on the client |
| A code from one host name is refused at another | The realm has no base URL, so each host name is its own issuer | Use one host name throughout, or set the [Realm base URL](/platform/realms/realm-base-url/) |

## Audit record

The user's sign-in writes `LOGIN` and its steps; the code's redemption writes a `TOKEN_ISSUED` record with
`grantType` `authorization_code`, naming the client, the scopes granted and the API. A refused redemption is a
`TOKEN_ISSUED` record with result `FAILED` and its `error`. The user's first consent is a change to their
`oauth2Consent`. See them in **Audit → Authentication**, or read the user's trail
([Read a user's or agent's trail](/audit-reports/audit-trail/read-a-trail/)).

## Good to know

- **PKCE is required of every app**, with the `S256` method. A request without it, or with the weaker `plain`
  method, is refused.
- **The return address is matched exactly** against the client's `redirectUris`. An unregistered address is never
  followed: the user sees an error page and the app hears nothing. A native app's loopback address
  (`http://127.0.0.1` or `http://[::1]`) may use any port.
- **A registered return address carries no answer parameters.** One whose query names `code`, `state`, `iss`,
  `error`, `error_description` or `error_uri` is refused when the client is saved.
- **A code works once, for one minute by default.** If a code is used twice, the second attempt is refused, and the
  tokens the first one bought are revoked as well.
- **A code shown to the wrong client, with another `redirect_uri`, or without the DPoP key it is bound to, is
  spent.** It may have been stolen, so nobody can redeem it afterwards.
- **A code is redeemed only at the issuer that gave it.** A realm reached under several host names, with no
  [base URL](../../../../platform/realms/realm-base-url/), has one issuer per host name, and a code from one is refused
  under another. It stays unspent, so the app can still redeem it at the right one.
- **`dpop_jkt` binds the code to the app's [DPoP](../../client-security/dpop/) key** (RFC 9449 §10): only a token request with a proof
  by that key redeems it. A [pushed request](../../client-security/pushed-authorization-requests/) sent with a DPoP proof is bound to
  that key without naming it.
- **The user must still be there.** A code is refused once the user can no longer be issued tokens, or once the
  session they signed in with has ended.
- **Every token names an API.** With no `resource` in the request and no `defaultAudience` on the client, the
  request is refused with `invalid_target`.
- **`keys:admin` goes only to an administrator of the realm.** Anyone else who signs in for it is refused with
  `access_denied`.
- **An agent's client can't use this grant.** An agent acts for a user through [token exchange](../../tokens/token-exchange/)
  or [backchannel authentication](../../../agents/backchannel-authentication/), never by signing in as them.

## Reference

### Errors

Where the realm can't trust the return address, it shows the user its own error page and tells the app nothing: an
unknown client, a missing or unregistered `redirect_uri`, or a client that may not use this grant. Every other
refusal goes back to the app's return address, with `error`, `state` and `iss`.

| Error | Where | When |
|---|---|---|
| `invalid_request` | Sign-in | A required parameter is missing or malformed, such as `code_challenge`, or a `code_challenge_method` other than `S256` |
| `unsupported_response_type` | Sign-in | `response_type` is anything but `code` |
| `unauthorized_client` | Sign-in | The client is an agent's |
| `invalid_scope` | Sign-in | A scope the client or the realm doesn't hold |
| `invalid_target` | Sign-in | A `resource` the client may not name, or none and no default |
| `login_required` | Sign-in | `prompt=none` and the user would have to sign in |
| `consent_required` | Sign-in | `prompt=none` and the user would have to consent |
| `access_denied` | Sign-in | The user refused, can't be issued tokens, or asked for `keys:admin` without being an administrator |
| `invalid_grant` | Token | The code is unknown, expired, already redeemed, another client's or another issuer's; the `redirect_uri`, verifier or DPoP key doesn't match; or the user or their session is gone |

## Related

- [Sign users in to a web app](../../../guides/sign-in-to-apps/sign-in-web-app/): the task, start to finish.
- [Sign users in to a single-page app](../../../guides/sign-in-to-apps/single-page-app/): the same, for an app with
  no secret.
- [Check quietly whether a user is signed in](../../../guides/sign-in-to-apps/silent-sign-in-check/): `prompt=none`
  in practice.
- [OpenID Connect sign-in](../openid-connect/): what the app learns about who signed in.
- [Pushed authorization requests](../../client-security/pushed-authorization-requests/): keep the request out of the browser.
