Device-code Sign-in
How a device without a keyboard (a TV) signs in: it shows a short code, a signed-in session on another device approves it, and the device's poll receives its own token. The flow follows RFC 8628.
On this page
Quick Reference#
Enable Features::deviceCode() ('device-code'). {prefix} is the route_prefix config value.
| Endpoint | Auth | Does |
|---|---|---|
POST {prefix}/auth/device/code |
none | The device asks for a code pair. |
POST {prefix}/auth/device/token |
none | The device polls until the code is decided, then receives its token. |
GET {prefix}/auth/device/{user_code} |
auth:sanctum |
The approver reads which device is asking. |
POST {prefix}/auth/device/{user_code}/approve |
auth:sanctum |
The approver signs the device in. |
POST {prefix}/auth/device/{user_code}/deny |
auth:sanctum |
The approver refuses the device. |
| Setting | Default | Meaning |
|---|---|---|
device_code.code_ttl |
600 |
Seconds a code pair lives. |
device_code.interval |
5 |
Seconds a device is told to wait between polls. |
device_code.slow_down_step |
5 |
Seconds added to the interval for a poll that came too early. |
device_code.verification_uri |
none | The page the device shows beside the code; required. |
device_code.token_abilities |
null: [required_ability] when set, else ['device'] |
The abilities of the minted token; never * unless you list it. |
device_code.token_lifetime_minutes |
129600 |
Lifetime of the minted token (ninety days). |
device_code.max_token_age |
null |
Seconds; an approval from an older token answers 403. |
Introduction#
A television has no keyboard worth typing a password on. With the device-code sign-in the TV asks the backend for a code pair, shows the short user_code (and a QR code and URL built from verification_uri), and polls. A person already signed in on a phone looks the code up, sees which device is asking, and approves it. The TV's next poll receives a token and lands signed in. Throughout this document {prefix} is config('magic-starter.route_prefix').
Feature: Features::deviceCode() ('device-code'). None of the routes in this document is registered while the feature is off, and the gate is read when the routes load, so a route:cache freezes it. The installer offers it as device-code and publishes create_device_codes_table.php with it.
The mint never goes through the login response: the approving session already proved the account, and a two-factor challenge on a TV would ask it for a code it cannot type. Every answer of the two device endpoints carries Cache-Control: no-store.
Configuration#
Enable the feature in config/magic-starter.php:
'features' => [
\AnilcanCakir\MagicStarter\Features::deviceCode(),
],
The device_code block. Laravel merges a published config one level deep, so a block of your own replaces the shipped one whole; every number you leave out, set to null or set below one falls back to its default below.
| Key | Env | Default | Meaning |
|---|---|---|---|
code_ttl |
MAGIC_STARTER_DEVICE_CODE_TTL |
600 |
Seconds a code pair lives; also the expires_in the device is told. |
interval |
MAGIC_STARTER_DEVICE_CODE_INTERVAL |
5 |
Seconds the device is told to keep between polls. |
slow_down_step |
MAGIC_STARTER_DEVICE_CODE_SLOW_DOWN_STEP |
5 |
A poll that arrives fewer than interval - 1 seconds after the previous one (never below one) is answered slow_down and the stored interval grows by this many seconds. The second of tolerance absorbs jitter, since the poll time is stored to the second. |
verification_uri |
MAGIC_STARTER_DEVICE_CODE_VERIFICATION_URI |
none | The page the device shows beside the code. The QR code it draws carries verification_uri_complete, which is this value plus ?code=<user_code> (&code= when the value already has a query). Issuing a code throws while it is unset. |
token_abilities |
none | null |
The Sanctum abilities of the minted token. Left null, the token carries [required_ability] when that is set, else ['device'], so a device token passes the ability gate but cannot approve another device. A list you set is minted as given: one holding * lets a device approve other devices. |
token_lifetime_minutes |
MAGIC_STARTER_DEVICE_CODE_TOKEN_LIFETIME |
129600 |
Minutes the minted token lives, ninety days; sanctum.expiration still applies on top. |
max_token_age |
MAGIC_STARTER_DEVICE_CODE_MAX_TOKEN_AGE |
null |
Seconds. Lookup, approval and denial from a token older than this answer 403 forbidden; null is no limit. |
Request a Code#
Endpoint: POST {prefix}/auth/device/code
Middleware: throttle:magic-starter-device-issue. No bearer.
Request:
{
"device_name": "Living room TV"
}
device_name is optional, a string of at most 60 characters. It is what the device calls itself; the approver sees it as reported_name and it names the token only when the user agent says nothing better.
Response (200):
{
"device_code": "<43 random characters>",
"user_code": "BCDF-GHJK",
"verification_uri": "https://app.example.com/link",
"verification_uri_complete": "https://app.example.com/link?code=BCDF-GHJK",
"expires_in": 600,
"interval": 5
}
The device_code is the device's secret and leaves only through this answer; the database keeps its sha256 hex. The device shows user_code, draws a QR code from verification_uri_complete, and polls with device_code.
Response (400): {"error": "invalid_request"} when device_name is not a string of at most 60 characters.
Poll for the Token#
Endpoint: POST {prefix}/auth/device/token
Middleware: throttle:magic-starter-device-token. No bearer.
Request:
{
"device_code": "<the device code>"
}
Response (200): the shape a login gives, so the Flutter client completes it through completeSignIn:
{
"data": {
"user": {
"id": "9b1f...",
"name": "Ada",
"email": "[email protected]"
},
"token": "1|abc..."
},
"message": "Login successful"
}
Response (400), every other outcome: {"error": "<code>"} with one of:
error |
Meaning |
|---|---|
authorization_pending |
Nobody has decided the code yet; poll again after interval. |
slow_down |
The poll came more than a second before interval had passed; the interval grew by slow_down_step, so wait the longer time. The limiter answers the same code with HTTP 429. |
access_denied |
The approver refused the code. |
expired_token |
The code is unknown, past expires_in, or already traded for its token. |
An unknown, expired and spent code all answer expired_token, and so does a device_code that is missing, not a string or longer than 255 characters: the poll has no field errors and is no oracle for which codes exist. After a mint every later poll answers expired_token.
The mint runs under a row lock and happens once. The token is named from the issuing user agent (<app or browser> (<platform>), else the reported name, else Device), carries token_abilities, lives token_lifetime_minutes, and stores the poll request's IP address and user agent. A scheduled account deletion is cancelled exactly as on a login.
Look Up a Code#
Endpoint: GET {prefix}/auth/device/{user_code}
Middleware: auth:sanctum, the required-ability gate, throttle:magic-starter-device-approve
The approver reads the code off the TV (or follows its QR code) and looks it up before deciding, so they can tell the screen is theirs. The code may be sent in any case and with any separator; see The User Code. The lookup never changes the row.
Response (200):
{
"user_code": "BCDF-GHJK",
"device": {
"agent": {
"browser": "",
"platform": "tvOS",
"app": "Watchools",
"is_desktop": false,
"is_mobile": false
},
"reported_name": "Living room TV"
},
"issued_at": "2026-12-03T10:00:00.000000Z",
"issue_country": "TR",
"approver_country": "TR",
"same_network": true
}
device.agent is the issuing user agent as the session list parses it (SessionAgent::parse). The issuing address and the raw user agent never leave. issue_country and approver_country are read from Cloudflare's CF-IPCountry header and are null when it is absent or XX; they are informational only. Any caller can send that header, and only Cloudflare in front overwrites it at the edge, so the package never decides anything on a country. same_network says whether the approver's address and the device's stand for one network (an IPv6 address stands for its /64, and an IPv4-mapped one such as ::ffff:198.51.100.7 for its IPv4 address).
Response (404): {"error": "invalid_code"}, identical for a code that is unknown, expired, already decided or spent.
Response (403): {"error": "forbidden"} when the caller may not decide a code at all, see Who May Decide.
Approve or Deny#
Endpoints: POST {prefix}/auth/device/{user_code}/approve and POST {prefix}/auth/device/{user_code}/deny
Middleware: auth:sanctum, the required-ability gate, throttle:magic-starter-device-approve
Approve request:
{
"entry": "typed",
"password": "secret"
}
| Field | Rule |
|---|---|
entry |
Required: typed when the person read the code off the screen and typed it, link when they followed the QR code or URL. |
password or code |
Required only when the account has confirmed two-factor, see Proximity and Step-up. |
Deny takes no body.
Response (204): the decision landed. An approval binds the code to the caller, so the device's next poll mints that account's token; a denial makes the next poll answer access_denied. Two decisions on one code are judged one after the other and only the first lands.
| Status | Body | When |
|---|---|---|
| 404 | {"error": "invalid_code"} |
The code is unknown, expired, already decided or spent. |
| 422 | {"error": "code_must_be_typed"} |
entry is link and the approver is not on the device's network. |
| 422 | validation errors | entry is invalid, or a step-up proof is wrong. |
| 423 | {"error": "step_up_required"} |
The account has confirmed two-factor and sent no proof. |
| 403 | {"error": "forbidden"} |
The caller may not decide a code. |
| 429 | {"error": "too_many_attempts"} |
An approver limit is spent. |
Who May Decide#
Lookup, approval and denial refuse with 403 forbidden unless the caller is a full account on a token that can do everything:
- the token can
*, so the['app']token a device received cannot sign another device in; - the user is not a guest;
- the token is younger than
device_code.max_token_age, when one is set (a token whose age cannot be read fails when a limit is set).
Proximity and Step-up#
Proximity. A device code reaches the approver two ways: typed from the screen, or through a link or QR code. A link can be forwarded to someone far away, who would then approve a stranger's device into their own account by habit. So an approval with entry: link succeeds only from the network that issued the code; from any other it answers 422 code_must_be_typed and the app asks the person to type the code from the screen. Typing the code proves they read it off the device, so entry: typed approves from anywhere. A guess at a code is bounded by its 34 bits and the approver limits.
Step-up. An approval signs a device into the account, so an account with confirmed two-factor has to prove itself again, with the same semantics as the password confirmation:
- no proof sent: 423
step_up_required, so the client knows to ask for one; passwordfor an account with a password, orcodefrom the authenticator for a password-less one, through the sharedConfirmsIdentityrules;- a wrong proof: 422 with the validation message, as a password confirmation answers.
An account without confirmed two-factor needs no proof.
The Sign-in Notification#
Every mint sends DeviceSignedInNotification to the account, once the token is committed. A dispatch that throws is reported through report() and the device still receives its token. It is queued and goes out on:
| Channel | When |
|---|---|
database |
Features::hasNotificationFeatures(); the row feeds GET notifications. |
onesignal |
Features::hasOnesignalFeatures(). |
broadcast |
With database; the live delivery of the database row (notification.created). |
mail |
Always; skipped for an account without an address. |
The row carries title, body, device (the token's label), token_id, issue_country and revoke_path (sessions/{token_id}), the path a client sends a DELETE to in order to sign that device out. That route exists with the sessions feature on, so enable it beside device-code; the mail cannot revoke by itself and points the person at the sessions list instead. The device label is partly the device's own, so the mail escapes it. The minted token's label also shows as name in the sessions list (GET sessions).
The texts live in lang/*/notifications.php under device_signed_in.
Rate Limits#
| Limiter | Limit | Key | Refusal |
|---|---|---|---|
magic-starter-device-issue |
10 / minute | address | 429 {"error": "slow_down"} |
magic-starter-device-token |
60 / minute | address | 429 {"error": "slow_down"} |
magic-starter-device-approve |
10 / 10 minutes, twice | the user, and the address | 429 {"error": "too_many_attempts"} |
Nobody is signed in on the device, so its limiters key on the address alone (an IPv6 address collapsed to its /64). The approver limit holds two separate budgets, one per account and one per address, shared by lookup, approval and denial, so a guess at a user code costs the same whichever endpoint makes it. One approval costs two to four calls (the lookup, a lookup after retyping the code, a 423 step-up and its retry), and the address budget is shared by every account behind one CGNAT address, hence ten rather than fewer.
The User Code#
Eight characters from BCDFGHJKLMNPQRSTVWXZ (twenty consonants: no vowel to spell a word, no digit to confuse with a letter), about 34 bits, shown as XXXX-XXXX. It is stored without the hyphen. Whatever a person typed is normalised before the lookup: upper-cased, then every character outside the alphabet dropped, so bcdf ghjk, BCDF-GHJK and bcdfghjk are one code. A code lives code_ttl seconds and decides once.
Host Setup#
- Set
MAGIC_STARTER_DEVICE_CODE_VERIFICATION_URIto the page the TV shows, one your web app or a Universal Link serves. Without it issuing a code throws. - Publish and run the migration (
php artisan magic-starter:installoffers it with the feature), which createsdevice_codes. - Schedule the prune.
DeviceCodeis a prunable model and the package does not schedule it; without the line, spent rows stay for ever:
Schedule::command('model:prune', [
'--model' => \AnilcanCakir\MagicStarter\Models\DeviceCode::class,
])->daily();
A row is pruned one day after its expires_at, whatever its status (Enums\DeviceCodeStatus: pending, approved, denied, consumed). With the audit feature on, a device code is never written to the audit trail, by its create, a poll or the prune: it is a live credential, and no audit.exclude entry is needed.
4. Enable sessions so the notification's revoke_path works, and set MAGIC_STARTER_REQUIRED_ABILITY if the host narrows its tokens.
5. Put a CDN such as Cloudflare in front when you want the country lines; without it they are null.
Overriding the Actions#
| Contract | Default action | Role |
|---|---|---|
IssuesDeviceCodes |
Actions\IssueDeviceCode |
issue(?string $reportedName, ?string $ip, ?string $userAgent, ?string $country): array. Opens a pending code and returns the answer the device shows. |
ExchangesDeviceCodes |
Actions\ExchangeDeviceCode |
exchange(string $deviceCode, Closure $mint): array|string. Judges one poll; returns {user, token} or an error code. |
ApprovesDeviceCodes |
Actions\ApproveDeviceCode |
find(), approve() and deny(): the approver's lookup and decision. |
Bind your own in a service provider, as for every other action contract:
$this->app->bind(ExchangesDeviceCodes::class, MyExchangeDeviceCode::class);
Gotchas#
| Mistake | Fix |
|---|---|
Leaving verification_uri unset |
Issuing a code throws; set MAGIC_STARTER_DEVICE_CODE_VERIFICATION_URI. |
Not scheduling model:prune for DeviceCode |
Rows are never deleted. Schedule it. |
Polling faster than interval |
The device is answered slow_down and its interval grows; wait the larger value. |
Sending entry: link from the phone on another network |
422 code_must_be_typed; ask the person to type the code. |
| Approving from the device's own token | 403 forbidden; only a token that can * decides. |
Logging user_code or device_code |
Never log either; they are credentials for the minutes they live. |
| Caching the routes before enabling the feature | The gate is read when the routes load, so a route:cache freezes it. |
Reading the device_code from the poll answer after a mint |
The code is spent; every later poll answers expired_token. |
Related Documentation#
- Sign-in Handoff: the sibling flow that carries a signed-in session to another origin.
- Authentication: the login answer the poll mirrors.
- Two-factor Authentication: the confirmed second factor that triggers the step-up.
- Notifications: the list and push the sign-in notice lands in.
- Profile: the sessions list a device is signed out from.
- Action Contracts: binding your own action.
- Configuration: the
featuresarray.