PREP WITH PROOF
Menu
IDENTITY & API SECURITY / PRACTICAL GUIDE

OAuth Device Authorization for CLIs: Polling and Security

Understand OAuth device authorization for CLI sign-in: separate codes, polling intervals, slow_down, expiry and phishing defenses. Includes an offline timing model.

THE QUICK ANSWER

Device authorization lets a client wait while a user approves access in a separate browser. The client polls with its device_code; the user enters a different user_code. A reliable CLI respects the polling interval, retains slow_down increases, stops on terminal responses and ties browser approval to a sign-in the user actually initiated.

The terminal waits while the browser handles approval

A CLI may run over SSH or on a machine where opening a local browser and receiving a callback is impractical. Device authorization moves the interactive approval to a browser the user can reach, while the original client waits for the authorization result. The password is entered at the authorization service, not into the waiting terminal.

The practical challenge is coordinating two experiences without confusing the user or overwhelming the token endpoint. A browser that says approval succeeded and a terminal that continues waiting are separate observations. Investigate which session, account and polling state each experience represents before starting another login.

This guide includes a small offline Python timing model tested locally with Python 3.12.14. It sends no HTTP requests, carries no codes or tokens, and does not authenticate an account. Its purpose is to make polling transitions and stopping conditions visible before implementing a provider-specific client.

Source: Auth0: device authorization flow and browser interaction ↗

Choose the flow the provider and environment support

An ordinary native application that can use an external browser and a supported redirect may use authorization code with PKCE. A remote terminal’s callback constraints can make that approach inconvenient, but inconvenience alone does not establish that a provider enables device authorization for every client type.

Check application registration, supported grants, scopes and organization policy first. GitHub documents a device flow for headless applications such as CLI tools and requires it to be enabled for the OAuth app. Other providers define their own eligible application types and setup requirements; endpoint paths should come from their documentation or validated metadata.

For a scheduled job without an interactive user, do not keep generating device codes in a loop. Decide whether the service supports an appropriate workload identity or another noninteractive mechanism. Device authorization is a user-approval experience, so its lifecycle should have an explicit owner and a clear reason to start.

Source: RFC 8252: OAuth for native applications ↗

Keep the device code and user code in different places

The initial response supplies device_code for the requesting client and user_code for the person approving access. It also provides verification_uri, expires_in and a polling interval. Some providers offer verification_uri_complete for a browser shortcut that embeds the user-facing session information.

Display the intended verification destination and user code clearly. Keep the device code out of terminal instructions, screenshots and routine telemetry. The device code belongs in the client’s token request; substituting the shorter user code there confuses two different protocol roles.

A QR code or convenient browser link reduces typing, but the user still needs to understand which sign-in is being approved. Preserve a readable fallback and enough session context to compare the browser experience with the terminal that started it. Avoid making the user choose between several indistinguishable pending sessions.

ValueWho uses itImplementation boundary
device_codeWaiting clientToken request; keep private
user_codeApproving personShow with the verification destination
expires_inClient timing policyBound this pending session
intervalPolling schedulerMinimum wait between requests

Source: Microsoft identity platform: device-code request and response ↗

Treat token acquisition as a provider-specific contract

The client makes token requests using the device-code grant type and the original device code. Required client identification, authentication and request parameters depend on the registered application and authorization server. Do not paste a client secret into a public CLI simply because a different example used one.

Microsoft recommends supported authentication libraries where possible. A maintained library can own token acquisition and cache behavior while the application supplies a clear user experience and cancellation policy. If implementing the protocol directly, isolate HTTP parsing, timing decisions, token handling and user messaging so that each can be tested independently.

Do not equate the arrival of an arbitrary access-token-shaped value with complete application identity validation. Use the provider’s supported token and resource contract. The offline model below marks a simulated success only; it cannot verify issuer, account, scopes, audience, token type, refresh eligibility or storage security.

Source: Microsoft identity platform: device-code request and response ↗

A pending response is a timing decision, not a failed login

RFC 8628 requires a wait before each polling request: use the returned interval, or five seconds when it is absent. authorization_pending permits continued polling. slow_down adds five seconds to the interval for subsequent requests; the increase must persist. Other error responses stop polling. A connection timeout requires a reduction in polling frequency; doubling is a recommended backoff approach.

Keep protocol outcomes separate from transport outcomes. An HTTP timeout does not tell you that the user denied access, and a malformed proxy response is not an authorization_pending result. Decode only a response that matches the expected endpoint contract; classify unsupported or invalid responses explicitly.

Use a monotonic clock for local scheduling. Decide how authorization-request elapsed time is charged against the session budget; starting a conservative local budget before the request avoids silently granting extra waiting time after a slow response. Recheck cancellation and expiry before each request and bound the request’s own timeout by the remaining budget.

Source: RFC 8628: OAuth device authorization grant and polling rules ↗

An offline model you can trace without credentials

Save this as device_poll.py and run python3 -B device_poll.py. Here elapsed zero is when authorization metadata is ready; pass the remaining lifetime after charging any initial authorization-request time against the earlier conservative budget. start accepts positive finite durations; a missing interval becomes five seconds. The fake demo gives every response zero duration so that scheduling is easy to inspect.

after_response receives the time a simulated response finished. The next request is scheduled after that response, which is a conservative scheduling choice. The caller must also enforce request-start timing. wait_seconds returns None when a session is terminal or its earliest next request would reach or exceed the local deadline.

The model retains every slow_down increase, doubles the current gap after a simulated connection timeout, and lets the local deadline win over a late success. cancel stops a waiting session. These are timing and local-policy demonstrations, not an HTTP client or a complete validation layer for untrusted provider responses.

# Offline timing model only: no HTTP, codes, tokens or credential storage.
from dataclasses import dataclass
import math


def seconds(value, name):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f'{name} must be a positive finite number')
    try:
        value = float(value)
    except OverflowError as exc:
        raise ValueError(f'{name} must be finite') from exc
    if not math.isfinite(value) or value <= 0:
        raise ValueError(f'{name} must be a positive finite number')
    return float(value)


@dataclass(frozen=True)
class PollState:
    interval: float
    due: float
    deadline: float
    status: str = 'waiting'


def start(expires_in, interval=None):
    lifetime = seconds(expires_in, 'expires_in')
    gap = 5.0 if interval is None else seconds(interval, 'interval')
    # Times are elapsed seconds from the chosen conservative session origin.
    return PollState(gap, gap, lifetime)


def valid_clock(now):
    if isinstance(now, bool) or not isinstance(now, (int, float)):
        raise ValueError('now must be finite and nonnegative')
    if not math.isfinite(now) or now < 0:
        raise ValueError('now must be finite and nonnegative')


def wait_seconds(state, now):
    valid_clock(now)
    if state.status != 'waiting' or now >= state.deadline:
        return None  # Stop; do not start another request.
    if state.due >= state.deadline:
        return None  # Even the earliest permitted next request is too late.
    return max(0.0, state.due - now)


def after_response(state, now, outcome):
    valid_clock(now)
    # Call after a simulated request that started at or after state.due.
    if state.status != 'waiting' or now < state.due:
        raise ValueError('No response is expected at this point')
    if now >= state.deadline:
        return PollState(state.interval, now, state.deadline, 'expired')
    if outcome == 'success':
        return PollState(state.interval, now, state.deadline, 'complete')
    if outcome == 'authorization_pending':
        gap = state.interval
    elif outcome == 'slow_down':
        gap = state.interval + 5.0
    elif outcome == 'connection_timeout':
        gap = state.interval * 2.0  # This model's backoff choice.
    else:
        # Includes access_denied, expired_token and unrecognized errors.
        return PollState(state.interval, now, state.deadline, 'stopped')
    return PollState(gap, now + gap, state.deadline)


def cancel(state):
    if state.status != 'waiting':
        return state
    return PollState(state.interval, state.due, state.deadline, 'cancelled')


if __name__ == '__main__':
    state = start(expires_in=90)
    elapsed = 0.0
    for outcome in ['authorization_pending', 'slow_down',
                    'authorization_pending', 'connection_timeout', 'success']:
        delay = wait_seconds(state, elapsed)
        if delay is None:
            break
        elapsed += delay  # Fake clock; responses take zero time in this demo.
        print(f'{elapsed:g}s request -> {outcome}')
        state = after_response(state, elapsed, outcome)
    print('Final state:', state.status)

Read the trace as a sequence of state changes

The default trace sends requests at elapsed seconds 5, 10, 20, 30 and 50. The response at second 10 increases the gap from five to ten seconds. The following pending response keeps that ten-second gap. The timeout at second 30 doubles it to twenty before the simulated success at second 50.

If a session has only twenty seconds available and the earliest next request is due at second 20, this model stops rather than starting at the expiry boundary. It also refuses to schedule another request after denial, an unrecognized error, success or cancellation. A production driver must translate the stop into an accurate message and release its own pending work.

Test the scheduler with a fake clock rather than real sleeps. Assertions should cover exact boundaries, several consecutive slow_down responses, timeout backoff after an earlier slowdown, cancellation during a wait and a response arriving after the local deadline. These cases reveal state-reset bugs that a single successful sign-in rarely exposes.

5s request -> authorization_pending
10s request -> slow_down
20s request -> authorization_pending
30s request -> connection_timeout
50s request -> success
Final state: complete

Check provider details instead of assuming every response is identical

GitHub documents slow_down behavior, app enablement errors and the device-code grant type. Microsoft documents its own endpoints, registration parameters and sign-in responses. Google’s limited-input device documentation describes a separate setup and supported scope list. Copying one provider’s scopes, client ID or request body into another provider’s endpoint is not a portable integration.

Use returned expiration and interval values rather than hardcoding a familiar example’s session length. Confirm whether refresh tokens are available for the selected application and scopes. An expired pending device session and an expired access token are different lifecycle events; one does not automatically describe the other.

Collect redacted transition logs such as session started, poll pending, polling slowed and authorization stopped. Avoid raw request bodies, token responses, verification links containing codes and debugging commands that expose secrets in shell history. A useful diagnostic record identifies the transition and timing without preserving the credential material.

Source: GitHub: OAuth app device flow and error handling ↗

A genuine sign-in page can still authorize the wrong session

Microsoft’s device-code phishing research describes attackers persuading people to approve a device session the attacker initiated. The browser can be on a legitimate identity-provider domain while the resulting authorization benefits a different waiting client. Checking the domain alone does not prove that the user intended that particular session.

Ask users to start sign-in from the application they intend to authorize and compare the code and application details. A code received unexpectedly in email, chat or a supposed meeting invitation should not become a routine approval step. Explain that completing browser authentication can grant the waiting client access.

For the CLI experience, keep the prompt tied to the action the user just requested. When a session expires or is cancelled, stop presenting its code as usable. A new attempt should be a deliberate new interaction, with fresh instructions, so that stale terminals and browser tabs do not blur session ownership.

Source: Microsoft Threat Intelligence: device-code phishing research ↗

Organization policy is part of the integration

Microsoft Entra Conditional Access can target device code flow, and Microsoft recommends allowing it only where necessary. A policy block is an administrative decision to investigate with the organization’s identity team, not a transport error to overcome by polling faster or switching to an unrelated client registration.

Document the intended users, applications and operating environments before enabling the flow. Review permissions and session handling with the same care as the browser experience. Avoid broad configuration changes merely to make one developer’s test succeed; validate the intended supported path and retain a useful error when it is unavailable.

The implementation is ready when timing, cancellation and expiry are predictable, provider-specific acquisition uses the supported contract, and users can tell which session they are approving. Validate those properties separately from the happy-path token response.

Source: Microsoft Entra: Conditional Access authentication-flow controls ↗

KEEP THESE THREE THINGS

Your next steps

  1. Confirm the provider, registration and policy support device authorization for the intended CLI environment.
  2. Keep the device code private and make user approval visibly belong to the session the user initiated.
  3. Test polling transitions with a fake clock, then validate transport, token handling and cancellation through the provider-supported implementation.

Sources & official resources

Linked resources checked on 2026-10-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →