# Device authorization

> A TV, a kiosk or a command-line tool signs a user in by showing a short code they enter on their phone or computer.

Some devices can't show a browser, or make typing a password painful: smart TVs, game consoles, kiosks, printers and
command-line tools. With device authorization, the device shows a short code such as `BCDF-GHJK` and an address. The
user opens the address on their phone or computer, signs in, types the code and allows the device, which then gets
its tokens.

It's for apps a user signs in to. An AI agent's client can't use it: an agent acts for a user through
[token exchange](../../tokens/token-exchange/) or [backchannel authentication](../../../agents/backchannel-authentication/),
never by signing in as them.

## Before you begin

- **Who can do it:** a realm administrator (a group holding `RealmOwner`) turns the grant on; `RealmViewer` can read
  the settings but not change them. The device then calls the realm with its own client ID.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** the device's app is registered ([Register an app](../../register-an-app/)), usually as a public client.

## How it works

The device asks the realm for two codes: a long **device code** it keeps, and a short **user code** of eight letters
that it shows the user. Meanwhile it asks the realm every few seconds whether the user has answered.

**1. The device asks for its codes** at the realm's device authorization endpoint, as any client authenticates (a
public client sends only its `client_id`):

```sh
curl https://foobar.cvyuh.com/oauth2/device_authorization \
  -d client_id=living-room-tv \
  --data-urlencode 'scope=openid profile'
```

```json
{
  "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",
  "user_code": "BCDF-GHJK",
  "verification_uri": "https://foobar.cvyuh.com/device",
  "verification_uri_complete": "https://foobar.cvyuh.com/device?user_code=BCDF-GHJK",
  "expires_in": 600,
  "interval": 5
}
```

The device shows `user_code` and `verification_uri`, or a QR code of `verification_uri_complete`, which fills the
code in for the user.

**2. The device polls the token endpoint** every `interval` seconds:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -d grant_type=urn:ietf:params:oauth:grant-type:device_code \
  -d client_id=living-room-tv \
  -d device_code=GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS
```

Until the user answers, it's told to wait. Once they allow it, the answer is a normal token response.

## Set it up

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

1. Turn the grant on for the realm: add `urn:ietf:params:oauth:grant-type:device_code` to its `grantTypes` with
   `PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`. Read the realm's settings first with `GET` on the same address, and send back the whole list with the new value
   added: **a list you send replaces the realm's list.**
2. Add the same grant to the device app's client in `https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client`.

| Where | Setting | What it does |
|---|---|---|
| Realm | `grantTypes` includes `urn:ietf:params:oauth:grant-type:device_code` | Off by default. While it's on, discovery publishes `device_authorization_endpoint` |
| Client | `grantTypes` includes the same | Lets this device app use it |
| Realm | `deviceCodeLifetimeSecs` | How long the codes live (default 600) |
| Realm | `devicePollIntervalSecs` | The pace a device is told to keep (default 5) |
| Realm | `deviceMissesPerSession`, `deviceMissesPerAddress` | Wrong codes allowed per 15 minutes from one session or one address |
| Realm | `deviceMissesPerRealm` | The realm-wide level at which the realm records an alert |

## What the user sees

The user opens `https://foobar.cvyuh.com/device`, signs in if they aren't already, and types the code (or arrives with
it filled in from the QR code). The realm shows the app's name and what it asks for, and the user allows or refuses
it. The device's screen moves on by itself once it next polls.

| What the user sees | Why | What to do |
|---|---|---|
| "that code is not one waiting to be allowed" | A mistyped code, one already used, or one past its ten minutes | Check the code on the device; if it has expired, start again on the device |
| "too many wrong codes; wait a few minutes and try again" | Too many wrong codes from this session or this address | Wait, then type the code shown on the device |

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `deviceCodeLifetimeSecs`: how long both codes live | 600 (ten minutes) | 10 to 1,800 |
| `devicePollIntervalSecs`: the pace a device keeps | 5 | 1 to 60; each `slow_down` adds 5 |
| `deviceMissesPerSession`: wrong codes per session, per 15 minutes | 5 | 1 to 10,000 |
| `deviceMissesPerAddress`: wrong codes per address, per 15 minutes | 10 | 1 to 10,000 |
| `deviceMissesPerRealm`: the realm-wide alert level | 100 | 1 to 10,000 |
| User code | eight letters, twenty consonants | fixed |

## Good to know

- **User codes are hard to misread.** They use twenty consonants only, so they never spell a word and no two letters
  look alike. Case, dashes and spaces don't matter when the code is typed.
- **Both codes live ten minutes** by default, and a code is answered once.
- **Guessing is bounded.** After `deviceMissesPerSession` wrong codes from one session, or `deviceMissesPerAddress`
  from one address, within fifteen minutes, no code is read from them for the rest of the window. Lower them for a
  realm that sees guessing; keep them high enough that a user who mistypes isn't held up.
- **Polling is paced.** A device that asks again inside its interval is told `slow_down`, and its interval grows by
  five seconds. Asking again too soon slows it further. A device that waits the full interval is answered.
- **A device code is redeemed once.** If the same device code is redeemed a second time, the second request is
  refused, and the tokens the first one received are revoked too, since one of the two was a copy.
- **Allowing a device is recorded like any consent.** The user sees it among their apps and can remove it. Unless
  they allowed offline access, the device's access ends with the session they used to allow it.

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| The device is refused with `unauthorized_client` | The grant is on for the realm but not the client, or the other way round | Add `urn:ietf:params:oauth:grant-type:device_code` to both `grantTypes` lists |
| The device keeps getting `slow_down` | It polls faster than `interval`, and each early poll adds five seconds | Wait the full `interval` the last answer gave |
| The user is told the code isn't waiting | The code expired, or was typed into another realm's page | Start again on the device, and open the address it shows |

## Audit record

The user's sign-in at `/device` writes the usual sign-in records (`LOGIN` and its steps), and the device's tokens
write a `TOKEN_ISSUED` record, with `grantType` `urn:ietf:params:oauth:grant-type:device_code`. Every poll the realm
answers with an error, `authorization_pending` included, is a `TOKEN_ISSUED` record with result `FAILED` and its
`error`, under the device's client. 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/)).

## Reference

### Errors

While the device polls:

| Error | What it means | What the device does |
|---|---|---|
| `authorization_pending` | The user hasn't answered yet | Poll again after `interval` |
| `slow_down` | It polled too soon | Add five seconds to its interval, then poll again |
| `access_denied` | The user refused | Stop, and tell the user |
| `expired_token` | The codes ran out before the user answered | Start again with new codes |
| `invalid_grant` | The device code isn't one this client was given, or it was already redeemed | Start again with new codes |

At the device authorization endpoint itself, a client that may not use the grant, or an agent's client, is refused
with `unauthorized_client`. A scope or a resource the client may not ask for is refused with `invalid_scope` or
`invalid_target`.

## Related

- [Sign in a TV or command-line tool](../../../guides/sign-in-to-apps/sign-in-a-tv-or-cli/): the task, start to finish.
- [Refresh tokens](../refresh-tokens/): keep a device signed in without a new code.
- [Authorization code with PKCE](../authorization-code/): the sign-in for devices that do have a browser.
