This lesson combines 3 topics: Why a CLI needs its own login flow, RFC 8628 — Device Authorization Grant step by step, Designing the
user_codeand the confirmation page.
Learning Objectives
- Understand why the "standard" Authorization Code flow of a web app cannot be used as-is for a CLI
- List and compare 5 ways a CLI can authenticate a user or a machine
- Read the output of a device-flow-style
logincommand and know which step each line corresponds to - Know which flow popular CLIs (GitHub CLI, AWS CLI, Azure CLI, gcloud) choose and why
- Have a decision framework for choosing the flow of a new CLI (DevCLI from ACME Cloud)
- Know the exact request/response of the device authorization endpoint and the token endpoint per RFC 8628
- Understand the meaning and default values of
expires_inandinterval - Correctly handle the 4 device-flow-specific error codes:
authorization_pending,slow_down,access_denied,expired_token - Draw the complete sequence diagram of the device flow
- Compare device flow with Authorization Code to know what is "lost" and what "makes up for it"
- Choose the charset, length, and format of the
user_codebased on the recommendations in RFC 8628 §6.1 - Calculate entropy and the probability of a correct guess given rate limiting and expiry
- Understand why the
device_codemust have high entropy while theuser_codedoes not - Design a verification page and consent screen with enough information for the user to spot an unexpected request
- Know when to use
verification_uri_completeand QR codes, and the risks that come with them
Part 1: Why a CLI needs its own login flow
1. The problem: a CLI is not a web app
In the Login Flow Design course, the BFF is a confidential client: it runs on a server, keeps a client_secret, and has a fixed redirect_uri on its own domain. A CLI is completely different:
Three consequences:
- A CLI is a public client. Any "secret" embedded in the binary is effectively public. So a CLI must use PKCE or a grant that needs no secret.
- No web-style redirect URI. The IdP cannot redirect back to "the terminal". The CLI needs another channel to receive the result: either open a small web server on
127.0.0.1(loopback), or ask periodically (polling) whether the user has approved (device flow). - There may be no browser. When a developer SSHes into a server, runs inside a container, or the CLI runs on a Smart TV, there is no browser to open. The user has to use a second device (laptop, phone).
Self-check question: if you embed a
client_secretin thedevclibinary and publish it to npm, who can use that secret? (Answer: anyone who downloads the package and reads the binary.)
2. Five ways a CLI can authenticate
| # | Method | Who authenticates | Browser? | Supports IdP SSO/MFA | Notes |
|---|---|---|---|---|---|
| 1 | API key / Personal Access Token (PAT) pasted into the CLI | The user creates the token on the web | No (at use time) | Indirectly (when creating the token) | Simple, but tokens are usually long-lived and easily leaked in shell history |
| 2 | Resource Owner Password Credentials (ROPC): the CLI asks for username/password and sends them to the IdP | The CLI holds the password | No | Practically none (MFA, passkeys, federated SSO all break) | RFC 9700 §2.4: MUST NOT be used |
| 3 | Authorization Code + PKCE via loopback redirect (RFC 8252) | The IdP, in a browser on the same machine | Required, on the same machine | Full | Smoothest experience when a browser is available |
| 4 | Device Authorization Grant (RFC 8628) | The IdP, in a browser on any device | Required, but can be on another device | Full | Works over SSH/in containers; has its own phishing risk (Day 2, Part 3) |
| 5 | Workload identity / OIDC federation / mTLS | Infrastructure (CI provider, cloud) | No | Not applicable (no human) | For machines, not humans (Day 4, Part 1) |
Two principles follow:
- Humans logging in to a CLI: use (3) when there is a browser on the same machine, (4) when there is not or when you need to log in from another device. (1) is the fallback.
- Machines (CI, cron, servers) calling an API: use (5) or a narrowly scoped machine token. Do not run device flow in CI — there is nobody there to approve it.
Why ROPC is forbidden
RFC 9700 (OAuth 2.0 Security Best Current Practice, 01/2025) says it plainly: "The resource owner password credentials grant MUST NOT be used." Reasons:
- The CLI sees the user's real password → the password can leak through logs, crash dumps, plugins.
- The IdP no longer controls the login step → it cannot enforce MFA, passkeys, device/location-based sign-in policies, or SSO via an enterprise IdP.
- Users get "trained" to type their password somewhere other than the IdP's page → they become easier to phish.
3. Reading the output of a device-flow login command
This is typical output when running the login command of a public CLI that uses device flow (the format matches real output; the command name and codes have been replaced):
$ <cli> login
> Visit https://example.com/device?user_code=WDJB-MJHT
Waiting for authentication...
Congratulations! You are now signed in.
Each line corresponds to a step in RFC 8628:
| Output line | What is happening behind the scenes |
|---|---|
| (before printing) | The CLI calls POST /device/code with client_id (and scope). The server returns device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval |
Visit https://…/device?user_code=WDJB-MJHT | The CLI prints verification_uri_complete (the URL with the code already embedded). Many CLIs also try to open the browser with this URL right away |
Waiting for authentication... | The CLI starts polling POST /token with grant_type=urn:ietf:params:oauth:grant-type:device_code and device_code. The server returns authorization_pending until the user approves |
| (user opens the link, signs in to the IdP, clicks "Approve") | The browser talks to the server; the CLI knows nothing about this step |
Congratulations! You are now signed in. | The next poll receives an access_token (and usually a refresh_token). The CLI stores the token on the machine (Day 2, Part 2) |
DevCLI uses a clearer closing line that also states the identity and scope so the user can spot a wrong account immediately: ✓ Logged in: dev@example.com (profile: default, team: team-platform).
Two subtle points:
- The
device_codenever appears on screen. It is the "key" to obtain the token, held only by the CLI. What the user sees is theuser_code, a short code for typing by hand. - The browser does not need to be on the same machine. The printed link can be opened on a phone. That is why device flow works over SSH.
4. What popular CLIs do
The information below was checked against the official documentation at the time of writing; behavior may change between CLI versions.
| CLI | Default when a browser is available | When there is no browser / you want to log in from another device | Source |
|---|---|---|---|
AWS CLI aws sso login | Authorization Code + PKCE (default since v2.22.0), callback to localhost (--redirect-port picks the port) | --use-device-code uses Device Authorization; --no-browser to not open the browser automatically | AWS CLI User Guide, aws sso login reference |
Azure CLI az login | Since v2.61.0: WAM (Web Account Manager) on Windows, browser sign-in on macOS/Linux | If the browser cannot be opened it falls back to the device code flow at https://aka.ms/devicelogin; force it with --use-device-code | Microsoft Learn: Sign in interactively with Azure CLI |
GitHub CLI gh auth login | Browser-based flow with a one-time OAuth device code (with a --clipboard flag to copy the code) | Same flow, open the link on another machine; or --with-token to read a PAT from stdin | GitHub CLI manual gh auth login |
gcloud gcloud auth login | Opens a browser on the same machine | --no-browser: the "remote bootstrap" flow — copy a command to a machine that has a browser and gcloud and run it there. Not the RFC 8628 device flow | gcloud reference auth login |
Lesson: there is no "one correct flow for every CLI". Major CLIs usually have both: loopback/browser as the default for the best experience, and device code as the fallback for environments without a browser.
5. Decision framework for DevCLI
ACME Cloud wants to launch devcli. Its users are developers; 30% run it in SSH/devcontainers; the IdP is its own authorization server auth.example.com.
Decisions for DevCLI (used throughout the course):
devcli login: try loopback + PKCE; if it detects that a browser cannot be opened (SSH_CONNECTIONvariable, noDISPLAYon Linux, running in a container), it automatically switches to device flow.devcli login --device: force device flow.devcli login --no-browser: does not change the flow, it only skips opening the browser and prints the URL for the user to open. (DevCLI does not use--use-device-code; that is an AWS CLI/Azure CLI flag.)- In CI: no
login; useDEVCLI_TOKENor OIDC federation.
6. Common design mistakes
| Mistake | Consequence | Correct approach |
|---|---|---|
Embedding a client_secret in the CLI and treating it as secret | Anyone can impersonate the client | Register the CLI as a public client; use PKCE / device flow |
| Asking for the password in the terminal (ROPC) | Loses MFA/SSO, password leaks | Always send the user to the IdP's page |
| Supporting only loopback | Developers on SSH/devcontainers cannot log in | Have device flow as the fallback |
| Running device flow in CI "for convenience" | The pipeline hangs waiting for approval, or someone approves blindly | Machine token or OIDC federation |
Printing the device_code to logs | Anyone reading the logs can get the token once the user approves | Print only the user_code and URL |
Questions to ask the IdP before choosing a flow
Before committing to a flow, check the IdP you use:
- Does it allow registering a public client (no secret)?
- Does it support PKCE S256, and can it be enforced for that client?
- Does it accept loopback redirects with any port (
http://127.0.0.1/callback)? - Can the Device Authorization Grant be enabled for this client only, and what are
expires_inandinterval? - Does it have a revocation endpoint (RFC 7009) and refresh token rotation?
- Do customer organizations have a policy that blocks device flow (e.g. Conditional Access)?
7. Terminology used in this course
| Term | Meaning in this course |
|---|---|
| Public client | A client that cannot keep secrets (CLI, mobile app, SPA). Has no real client_secret |
| Authorization Server (AS) | The server that issues tokens. In the examples: auth.example.com |
| Device client | The application that starts the device flow, here devcli |
device_code | The secret code the CLI uses to obtain the token when polling. Never shown to the user |
user_code | The short code shown to the user to enter in the browser |
| Verification URI | The page the user opens to enter the user_code, e.g. https://example.com/device |
| Polling | The CLI calls the token endpoint periodically to ask "has the user approved yet?" |
| Loopback redirect | A redirect to a temporary web server of the CLI on 127.0.0.1 |
| PKCE | Proof Key for Code Exchange (RFC 7636), binds whoever started the flow to whoever exchanges the code |
| Credential store | The OS secret store: Keychain, Credential Manager, Secret Service |
| Profile | A named set of login configuration (account, team, issuer) |
| OIDC federation | CI proves its identity with a token issued by the CI platform and exchanges it for short-lived credentials |
8. Course roadmap
The course is 1 week, 5 days. Each day combines 3 related topics into Parts.
| Week | Day | Topic | Question you can answer after studying |
|---|---|---|---|
| 1 | 1, Part 1 | Why a CLI needs its own flow | Which flow should my CLI use? |
| 1 | 1, Part 2 | RFC 8628 in detail | What do the CLI and the AS exchange, and how are errors handled? |
| 1 | 1, Part 3 | user_code and the confirmation page | How long should the code be, and what should the consent page show? |
| 1 | 2, Part 1 | Loopback + PKCE | How does a CLI receive a callback without a domain? |
| 1 | 2, Part 2 | Storing tokens on the developer machine | Where do tokens live, and what does logout do? |
| 1 | 2, Part 3 | Security | How do attackers abuse device flow? |
| 1 | 3, Parts 1-2 | Building the AS and the CLI | Write the code for both sides |
| 1 | 3, Part 3 | Existing IdPs | How do Auth0, Entra ID, GitHub, Keycloak support it? |
| 1 | 4, Part 1 | Token lifecycle, profiles, CI | Refresh, multiple accounts, CI with no human |
| 1 | 4, Part 2 | Debugging and operations | "I'm logged in but still Not authorized" — what now? |
| 1 | 4, Part 3 | Capstone | Write a complete spec and threat model |
| 1 | 5 | Final quiz | 30 questions covering the whole course |
Part 2: RFC 8628 — Device Authorization Grant step by step
1. Three roles and two channels
The core of RFC 8628: the two channels do not talk to each other directly. The RFC assumes the device has no way to receive a signal back from the browser. The only bridge is the user_code, which the user carries from the CLI screen to the browser. The CLI learns the result by asking the AS again periodically (polling).
The device authorization endpoint can be published in the AS metadata (RFC 8414) via the device_authorization_endpoint field, just as token_endpoint is published. The CLI should read the metadata instead of hard-coding URLs.
Example metadata (trimmed) that DevCLI reads from https://auth.example.com/.well-known/oauth-authorization-server:
{
"issuer": "https://auth.example.com",
"authorization_endpoint": "https://auth.example.com/authorize",
"token_endpoint": "https://auth.example.com/token",
"device_authorization_endpoint": "https://auth.example.com/device/code",
"revocation_endpoint": "https://auth.example.com/revoke",
"grant_types_supported": [
"authorization_code",
"refresh_token",
"urn:ietf:params:oauth:grant-type:device_code"
],
"code_challenge_methods_supported": ["S256"]
}
device_authorization_endpoint is registered by RFC 8628 §4 in the RFC 8414 metadata registry. If the AS does not publish this field, the CLI should report a clear error, "the IdP has not enabled device flow", instead of guessing the URL.
2. Step 1 — Device Authorization Request
POST /device/code HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
client_id=devcli&scope=openid%20offline_access%20deploy%3Aread
| Parameter | Required | Notes |
|---|---|---|
client_id | Yes (for public clients) | A public client sends only client_id. A confidential client authenticates as it does at the token endpoint (RFC 6749 §3.2.1) |
scope | No | The requested scope. DevCLI defaults to openid offline_access deploy:read; deploy:write is requested only via step-up when a command needs it (Day 4, Part 1). If omitted, the server uses the default openid offline_access deploy:read |
Rules worth remembering from RFC 8628 §3.1:
- Every request from the device MUST use TLS.
- Parameters sent without a value are treated as omitted; the AS ignores unrecognized parameters; each parameter appears at most once.
- The client SHOULD start device authorization only when the user asks for it (typing the
logincommand), not automatically at app startup or when an old session expires. Reason: every start triggers a series of polling requests.
3. Step 2 — Device Authorization Response
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",
"user_code": "WDJB-MJHT",
"verification_uri": "https://example.com/device",
"verification_uri_complete": "https://example.com/device?user_code=WDJB-MJHT",
"expires_in": 1800,
"interval": 5
}
| Field | Required | Meaning |
|---|---|---|
device_code | Yes | The secret code the CLI uses when polling. High entropy, never shown |
user_code | Yes | A short code for the user to type by hand |
verification_uri | Yes | The page the user opens in the browser. Should be short and memorable because the user may have to type it |
verification_uri_complete | No | A URL with the user_code embedded, used for QR codes or opening the browser directly |
expires_in | Yes | Lifetime (seconds) of both the device_code and the user_code |
interval | No | Minimum number of seconds between 2 polls. If absent, the client MUST use 5 |
Real-world example: GitHub returns expires_in = 900 (15 minutes) and interval = 5 for the OAuth app device flow (per GitHub Docs). The RFC example uses 1800 seconds. The specific numbers are the AS's decision (Part 3 of this lesson and Day 2, Part 3).
4. Step 3 — The user confirms in the browser
The CLI prints instructions: "Open https://example.com/device and enter the code WDJB-MJHT", or prints verification_uri_complete directly, or draws a QR code. In the browser:
- The user opens the verification page.
- Signs in to the IdP if not already signed in (MFA, passkeys, enterprise SSO all work because this is the AS's real page).
- Enters the
user_code(or the code pre-filled fromverification_uri_complete). - Reviews the consent screen: which client, which permissions, which device started the request.
- Clicks Approve or Deny.
RFC 8628 does not specify the UI for this step; it only gives security recommendations (Part 3 of this lesson and Day 2, Part 3).
5. Step 4 — Polling the token endpoint
Right after displaying the instructions, the CLI starts sending:
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code
&device_code=GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS
&client_id=devcli
grant_type=urn:ietf:params:oauth:grant-type:device_code is an extension grant defined by RFC 8628 (using the mechanism in RFC 6749 §4.5). client_id is required if the client does not authenticate in some other way.
Responses:
- Success: a standard RFC 6749 §5.1 response (
access_token,token_type,expires_in, optionallyrefresh_token,scope). - Not done yet / error: a standard RFC 6749 §5.2 error response (HTTP 400, JSON body with
error), with these specific codes:
error | Meaning | What the CLI must do |
|---|---|---|
authorization_pending | The user has not finished | Wait at least interval seconds (or 5s if absent), then poll again |
slow_down | Still waiting, but the client is polling too fast | Increase the interval by 5 seconds for this and all subsequent requests, then keep polling |
access_denied | The user clicked Deny | Stop polling, report an error |
expired_token | The device_code has expired | Stop polling. MAY start over, but SHOULD wait for the user to ask instead of restarting automatically |
Other codes (invalid_client, invalid_grant...) | Configuration or request error | MUST stop polling, report an error |
In addition, RFC 8628 §3.5 requires: on a connection timeout, the client MUST reduce its polling frequency before retrying; exponential backoff is recommended (e.g. double the interval after each timeout).
6. Complete sequence diagram
sequenceDiagram
autonumber
participant U as Dev (user)
participant C as devcli
participant AS as auth.example.com
participant B as "Browser (any device)"
U->>C: devcli login --device
C->>AS: POST /device/code (client_id, scope)
AS-->>C: 200 device_code, user_code, verification_uri, expires_in, interval
C-->>U: Prints "Open example.com/device, enter WDJB-MJHT"
loop Every interval seconds
C->>AS: POST /token (grant_type=device_code, device_code, client_id)
AS-->>C: 400 error=authorization_pending
end
U->>B: Open verification_uri
B->>AS: GET /device
AS-->>B: Sign-in page (MFA, SSO...)
B->>AS: Sign in, enter user_code
AS-->>B: Consent screen (client, scope, device)
B->>AS: Approve
C->>AS: POST /token (device_code)
AS-->>C: 200 access_token, refresh_token
C-->>U: ✓ Logged in: dev@example.com (profile: default, team: team-platform)Note: polling happens in parallel with the browser steps. The order in the diagram is for illustration only.
7. Compared with Authorization Code + PKCE
| Aspect | Authorization Code + PKCE | Device Authorization Grant |
|---|---|---|
| How the result returns to the client | Redirect to redirect_uri (with code) | The client polls the token endpoint |
| Needs a browser on the same device | Yes | No |
| Binding between the sending and receiving client | PKCE (code_verifier) + state | device_code held only by the client |
| CSRF protection on the callback | state | No callback, so no state needed |
| Specific risks | Hijacked redirect URI, mix-up | Remote phishing: an attacker gives the victim their own user_code (Day 2, Part 3) |
| Load on the token endpoint | 1 request | Many polling requests → needs rate limiting, slow_down |
8. Common implementation mistakes
| Mistake | Consequence |
|---|---|
Polling immediately without waiting for interval | Constant slow_down or getting rate limited |
Receiving slow_down but not permanently increasing the interval | Violates the RFC; the AS may block the client |
| Treating every 400 error as "pending" and polling forever | The CLI hangs indefinitely on misconfiguration (invalid_client) |
Automatically starting a new device flow on expired_token | Creates a loop generating codes nobody uses, increasing load and phishing risk |
| No overall timeout | The CLI hangs if the AS never returns expired_token |
Part 3: Designing the user_code and the confirmation page
1. Two codes, two purposes
RFC 8628 §5.2: because the device_code is not displayed, there is no UX reason to make it short, so it SHOULD use a very high-entropy code. Conversely, the user_code must be short enough to type, so its entropy is lower and must be compensated with rate limiting + a short expiry (§5.1).
Note the consequence in §5.1: if an attacker guesses a user_code correctly, they approve with their own account, so the victim's device receives a token bound to the attacker's account. This is the reverse of guessing a bearer token. It is not always economically worthwhile for the attacker, but it is still a privacy risk and can be dangerous if that account can control the device.
2. Charset per RFC 8628 §6.1
Users often enter the code on a phone, where switching case or switching to digits is slow. The RFC suggests:
- Use only letters A-Z, case-insensitive, no digits.
- Drop vowels to avoid accidentally forming real words (possibly offensive ones).
- Result: the base-20 charset
BCDFGHJKLMNPQRSTVWXZ. - You may add a hyphen for readability, e.g.
WDJB-MJHT: 8 significant characters, entropy 20^8. - All-digit codes also work well for locales that do not use A-Z keyboards, but they must be longer. RFC example: 9 digits
019-450-730, entropy 10^9.
When processing input, the server should strip hyphens and punctuation and uppercase the input before comparing (for the A-Z charset). Whether the user types wdjbmjht or WDJB MJHT, it must be accepted.
| Format | Example | Combinations | Bits of entropy (approx.) |
|---|---|---|---|
| 8 base-20 characters | WDJB-MJHT | 20^8 ≈ 2.56 × 10^10 | 34.5 |
| 9 digits | 019-450-730 | 10^9 | 29.9 |
| 6 digits (too short) | 482-913 | 10^6 | 19.9 |
3. Calculating the probability of a correct guess
RFC 8628 §5.1 gives an example: with a 128-bit symmetric key, an attacker must spend 2^96 work to have a 2^-32 chance of guessing correctly. With an 8-character base-20 code (~34.5 bits), achieving the same 2^-32 probability through random guessing means rate limiting and expiry may allow only about 5 attempts.
In practice there is one more factor: the attacker does not need to guess one specific code, only any code that is still valid. The probability per guess:
P(hit per guess) = number of active codes / total combinations
DevCLI example: at any time about 2,000 codes are pending, 8-character base-20 codes.
P(1 guess) = 2,000 / 2.56e10 ≈ 7.8e-8
Rate limit = 10 attempts/minute/IP, block IP after 50 wrong
Attacker has 1,000 IPs, at most 50 attempts per IP
Total attempts = 50,000
P(at least 1 hit) ≈ 50,000 × 7.8e-8 ≈ 0.4%
0.4% is not 0. So the server needs additional layers of protection:
- Rate limit by signed-in account on the verification page (the attacker must sign in before entering a code), not just by IP.
- Count wrong entries per account and lock temporarily.
- Short expiry (
expires_in) to reduce the number of active codes. - Anomaly detection: one account entering many different codes in a short time.
4. Generating codes securely
import { randomInt, randomBytes } from 'node:crypto';
const USER_CODE_CHARSET = 'BCDFGHJKLMNPQRSTVWXZ'; // base-20, RFC 8628 §6.1
/** user_code in XXXX-XXXX form, uses a CSPRNG (not Math.random). */
export function generateUserCode(): string {
let raw = '';
for (let i = 0; i < 8; i++) {
raw += USER_CODE_CHARSET[randomInt(USER_CODE_CHARSET.length)];
}
return `${raw.slice(0, 4)}-${raw.slice(4)}`;
}
/** device_code: 32 random bytes (256 bits), base64url. */
export function generateDeviceCode(): string {
return randomBytes(32).toString('base64url');
}
/** Normalize user input: drop every non-letter character, uppercase. */
export function normalizeUserCode(input: string): string {
return input.replace(/[^a-z]/gi, '').toUpperCase();
}
Notes:
randomIntfromnode:cryptouses a CSPRNG and avoids modulo bias.- When storing, use the normalized form (
WDJBMJHT) as the lookup key; the hyphenated form is for display only. - Check for collisions with active codes before issuing (unlikely but possible).
- Store a hash of the
device_codeinstead of plaintext (details in Day 3, Part 1).
5. The verification page
Goal: the user enters the code quickly with few mistakes, and recognizes if the request was not started by them.
Recommendations:
- Short, easy-to-type URL (
example.com/device), because the user may have to type it on a phone. - The input field auto-uppercases, accepts codes with or without the hyphen, and accepts pasting either the code or the URL.
- Require sign-in before entering the code, so rate limiting can be per account.
- Generic error message ("Invalid or expired code"), not distinguishing "wrong" from "expired" so as not to help code guessers.
- Accessibility: the input has a label, works with screen readers, and the code is shown in a monospace font.
- i18n: if your market uses non-Latin keyboards, consider a longer all-digit code.
6. The consent screen
After the code is validated, the AS shows a confirmation screen. RFC 8628 §5.4 recommends informing the user that they are authorizing a device and confirming that the device is in their possession; the AS SHOULD display information about the device so the user can notice if software is impersonating a device.
Each line has a reason:
| Information | Why it is needed |
|---|---|
| App name + "official" label | The user knows who they are granting access to |
| Easy-to-understand permission list | Avoids over-granting |
| IP and location of the initiating device | The user is in Ho Chi Minh City but the request comes from another country → sign of phishing |
| Time of initiation | The code was created 20 minutes ago but the user just ran the command → suspicious |
| Showing the code again | Especially important when using verification_uri_complete (section 7) |
| Clear warning sentence | Reduces the effectiveness of the "IT staff sent you a code" scenario |
7. verification_uri_complete and QR codes
verification_uri_complete (e.g. https://example.com/device?user_code=WDJB-MJHT) allows:
- The CLI to open the browser directly with the code pre-filled.
- Devices without a keyboard (TV, IoT) to draw a QR code to scan with a phone.
In exchange, the user no longer types the code themselves, so they are more likely to click "Allow" reflexively when they receive a link by email or message. RFC 8628 §5.4 stresses: for an AS that supports verification_uri_complete, confirming that the device is in the user's possession is even more important. The RFC's suggestion: show the code again in the flow and ask the user to check that it matches the code shown on the device.
Considerations for DevCLI:
| Context | Use verification_uri_complete? |
|---|---|
| The CLI opens the browser itself on the same machine | Yes, but the page still requires clicking confirm and shows the code again |
| The CLI runs over SSH and prints the link to the terminal | Yes, and also prints the code separately for the user to compare |
| Sending the link by email/chat to someone else | Never: this is exactly the phishing scenario |
8. Choosing expires_in
RFC 8628 §5.4: the code must live long enough for the user to grab a second device, open the page, and sign in (possibly with MFA), but short enough to reduce the value of codes obtained through phishing. A short-lived code does not stop a real-time interactive attacker, but it does limit codes sent via email or SMS.
| Value | Comment |
|---|---|
| 1800 seconds (RFC example) | Generous; suits first-time device setup where the user needs time |
| 900 seconds (GitHub device flow) | Balanced for a developer tool |
| 300-600 seconds | Suits internal CLIs with SSO already in place; reduces the phishing window |
DevCLI chooses 600 seconds, with an interval of 5 seconds.
9. Verification page test checklist
| # | Scenario | Expected result |
|---|---|---|
| 1 | Enter the code in lowercase, with spaces | Accepted |
| 2 | Enter an expired code | "Invalid or expired code" |
| 3 | Enter a code that was already approved | Same message, no state leaked |
| 4 | Consecutive wrong entries beyond the threshold | Temporarily blocked per account |
| 5 | Open verification_uri_complete while not signed in | After signing in, returns to the same code |
| 6 | Initiating IP in a different country from the browser | Prominent warning on the consent screen |
Review Questions
-
Why must a CLI distributed via npm/Homebrew be treated as a public client?
Show answer
The CLI binary sits on every user's machine, and anyone can unpack it and read the strings inside. A
client_secretembedded there is no longer secret, so the authorization server cannot use it to authenticate the client. Therefore the CLI registers as a public client and relies on mechanisms that need no secret: PKCE for loopback, or a one-timedevice_codefor device flow. -
What does RFC 9700 say about the Resource Owner Password Credentials grant? Give two reasons.
Show answer
RFC 9700 §2.4 states that this grant MUST NOT be used. Reasons: (1) the client sees the user's real password, increasing the leak surface (logs, crash dumps, plugins); (2) the IdP loses control of the login step, so it cannot enforce MFA, passkeys, federated SSO, or device-based policies; in addition, users get used to typing their password somewhere other than the IdP's page, making them easier to phish.
-
In the output
Visit https://example.com/device?user_code=WDJB-MJHT, which RFC 8628 parameter is being printed? Why doesn't the CLI print thedevice_code?Show answer
It is
verification_uri_complete(the URL with theuser_codeembedded). Thedevice_codeis the value the CLI uses to obtain the token when polling; anyone with thedevice_codecan get the token as soon as the user approves, so it must never be displayed or logged. The user only needs theuser_code, a short code to enter or confirm in the browser. -
Is
gcloud auth login --no-browserthe RFC 8628 device flow?Show answer
No. According to the gcloud documentation,
--no-browserdisplays agcloud auth login --remote-bootstrap=...command for the user to run on another machine that has a browser and gcloud installed, then paste the result back. This is a gcloud-specific mechanism, with nouser_codeand no polling of a token endpoint as in RFC 8628. This example shows you need to read each CLI's docs instead of assuming. -
DevCLI needs to support both loopback and device flow. State the conditions under which the CLI automatically switches to device flow.
Show answer
When the CLI detects that it cannot open a browser on the same machine: it is in an SSH session (
SSH_CONNECTION/SSH_TTYis set), Linux has noDISPLAY/WAYLAND_DISPLAY, it is running in a container/devcontainer, or the browser-opening command fails. The user can also force it with the--deviceflag. In CI it does not switch to device flow; instead it reports an error telling the user to use a machine token or OIDC federation. -
If the device authorization response has no
intervalfield, how long must the CLI wait between two polls? What is the source of this rule?Show answer
5 seconds. RFC 8628 §3.2 defines
intervalas OPTIONAL and states "If no value is provided, clients MUST use 5 as the default." §3.5 repeats it: before each new request, the client MUST wait at leastintervalseconds, or 5 seconds if absent. -
The CLI is polling every 5 seconds and receives
slow_down. What is the new interval, and how long does it apply?Show answer
10 seconds. Per RFC 8628 §3.5, on receiving
slow_downthe interval MUST be increased by 5 seconds "for this and all subsequent requests", meaning it applies to every subsequent poll in this session and never goes back to 5 seconds. If anotherslow_downarrives, add 5 again (15, 20...). -
Among the error codes returned by the token endpoint, which ones allow the CLI to keep polling? What does the RFC require for the others?
Show answer
Only
authorization_pendingandslow_downallow polling to continue. For any other error code (access_denied,expired_token,invalid_client,invalid_grant...), RFC 8628 §3.5 requires the client MUST stop polling and SHOULD react appropriately, for example by displaying the error to the user. -
Why doesn't device flow need a
stateparameter like Authorization Code does?Show answer
stateprotects against CSRF on the callback: it ensures the redirect response toredirect_uribelongs to the session that started it. Device flow has no redirect or callback to the client; the client fetches the result itself using adevice_codethat only it holds. The "whoever starts it receives the token" binding is guaranteed by the high-entropydevice_code(RFC 8628 §5.2). -
On receiving
expired_token, should the CLI automatically call/device/codeagain to get a new code?
Show answer
Not automatically. RFC 8628 §3.5 allows (MAY) starting over but recommends (SHOULD) waiting for user interaction before restarting, to avoid unnecessary polling. In practice the CLI should report "the code has expired, run devcli login again". Continuously generating codes also creates "orphan" codes that can be abused.
- Why does RFC 8628 suggest the charset
BCDFGHJKLMNPQRSTVWXZfor theuser_code?
Show answer
Users often enter the code on a phone, where switching case or switching to digits takes time. Using case-insensitive A-Z letters with no digits makes typing fast. Dropping vowels keeps random codes from accidentally forming real words (possibly offensive ones). The result is a set of 20 consonants (RFC 8628 §6.1).
- How many combinations and roughly how many bits of entropy does an 8-character base-20
user_codehave? Why is that acceptable when thedevice_codemust be much longer?
Show answer
20^8 ≈ 2.56 × 10^10 combinations, about 34.5 bits. The user_code is acceptable because it is constrained by rate limiting and a short expiry, so the actual number of attempts is very small (RFC 8628 §5.1). The device_code is not displayed, has no UX constraints, and guessing it gives the attacker the victim's token, so RFC 8628 §5.2 requires very high entropy.
- The server receives the input
wdjb mjhtfrom the user. How should it be normalized before lookup?
Show answer
Remove all whitespace, hyphens, and punctuation (characters the server added for readability), then uppercase everything, giving WDJBMJHT. RFC 8628 §6.1 recommends that the server strip punctuation and uppercase input when using the A-Z charset. The storage key should also be in normalized form.
- Name 3 pieces of information on the consent screen that help the user detect a device flow request they did not start.
Show answer
(1) The IP/location of the device that started the request: very different from the user's location is a red flag. (2) The time of initiation: a code created long before the user opened the page is suspicious. (3) The code shown again so the user can compare it with the code in their own terminal. Plus the warning "only continue if you just ran the command yourself". RFC 8628 §5.4 recommends displaying device information.
- Why does
verification_uri_completeincrease phishing risk, and how does the RFC suggest mitigating it?
Show answer
With the code embedded in the URL, the user does not need to type the code, so they are more likely to approve reflexively when they receive a link from someone else. RFC 8628 §5.4 says confirming that the device is in the user's possession is "particularly important" in this case, and suggests displaying the code during the flow and asking the user to check that it is the one shown on the device they are setting up.
Hands-on Exercises
Exercise 1: Observe a real CLI
Pick a CLI you have access to (gh, aws, az). Run the login command in device code mode (gh auth login, aws sso login --use-device-code, az login --use-device-code). Record each output line and map it to the table in section 3.
Expected output: a 2-column table "output line → RFC 8628 step", noting the interval and expiry time if the CLI prints them. Do not copy real tokens or codes into shared documents.
Exercise 2: Decision table for your product
For a hypothetical CLI at your company, fill in a table: user groups, share of SSH/container use, IdP in use, MFA/SSO requirements, whether there is CI. From that, choose a default flow and a fallback flow.
Expected output: a decision diagram like section 5 for your product, with 3-5 lines of reasoning.
Exercise 3: Call device flow with curl
With a test IdP that has device flow enabled (e.g. a test GitHub OAuth app with Device Flow enabled, or Keycloak running locally), call POST /device/code and poll POST /token with curl. Deliberately poll faster than interval to see slow_down.
Expected output: a time-ordered log of responses (containing no real tokens), showing when you received authorization_pending, slow_down, and the token. Note the new interval after slow_down.
Exercise 4: Write a polling state table
Write a CLI-side state machine table: states (waiting, backing_off, done, denied, expired, failed), events (each response type, timeout, Ctrl+C), actions, and next states.
Expected output: a 6 states × 7 events table, every cell filled, consistent with section 5.
Exercise 5: Probability spreadsheet
Write a spreadsheet (or script) that takes: the charset, code length, number of active codes, rate limits per IP and per account, and the number of IPs/accounts the attacker has. Output the probability of guessing at least one code within the expires_in window.
Expected output: a comparison of 3 configurations (8 base-20 characters, 9 digits, 6 digits) under the same assumptions, with a conclusion on which configuration meets your acceptable probability threshold.
Exercise 6: Wireframe the verification and consent pages
Draw wireframes of two screens for DevCLI: code entry and consent. Mark which recommendation from sections 5-7 each component corresponds to.
Expected output: 2 wireframes (ASCII or a drawing tool), each component annotated with its rationale, including the "invalid or expired code" error state.
References
- RFC 8628 — OAuth 2.0 Device Authorization Grant
- RFC 8252 — OAuth 2.0 for Native Apps
- RFC 9700 — OAuth 2.0 Security Best Current Practice
- AWS CLI — Configure IAM Identity Center authentication
- Azure CLI — Sign in interactively
- GitHub CLI — gh auth login
- gcloud auth login
- RFC 8414 — OAuth 2.0 Authorization Server Metadata
- GitHub Docs — Authorizing OAuth apps (Device flow)
- RFC 8628 §5 Security Considerations and §6.1 User Code Recommendations
- GitHub Docs — Device flow (expires_in, interval)