Runtime

OAuth Device Flow Login for Python CLIs

Add a secure ‘mytool login’ to a Python CLI with the OAuth 2.0 device authorization flow: request a code, poll correctly, handle every response and store tokens.

Updated

Your CLI needs to act on behalf of a user against an API protected by your organisation's identity provider — Okta, Entra ID, Auth0, Keycloak, GitHub. Asking for a username and password is out: it breaks with single sign-on and multi-factor authentication, and it trains people to type their most sensitive credential into programs. The standard answer, used by gh auth login, az login --use-device-code and most cloud CLIs, is the OAuth 2.0 device authorization grant (RFC 8628). The CLI shows a short code and a URL; the user approves in any browser, with whatever SSO and MFA their organisation requires; the CLI receives tokens. This guide implements that flow with httpx, handles every polling response correctly, and wires it into a login command. It belongs to the HTTP APIs topic.

Prerequisites

  • Python 3.10+ and httpx; keyring for token storage.
  • An OAuth client registered with your identity provider with the device grant enabled. You need its client ID, the device authorization endpoint and the token endpoint — all listed in the provider's discovery document at /.well-known/openid-configuration.
  • A public client (no client secret). CLIs cannot keep secrets; the device flow is designed for exactly that constraint.

How the device flow works

The flow involves three parties: your CLI, the authorisation server, and the user's browser — which can be on a different machine, such as a phone approving a login on a headless server.

The OAuth device authorization flow The CLI requests a device code, shows the user a short code and URL, the user approves in a browser, and the CLI polls until it receives tokens. The OAuth device authorization flow CLI Auth server User's browser POST /device/code user_code, verification_uri visit URL, enter code, approve POST /token (polling) access + refresh token The CLI never sees the password, and the browser can be on a different machine entirely.
  1. The CLI POSTs its client ID and requested scopes to the device authorization endpoint.
  2. The server returns a device_code (secret, for the CLI), a short user_code (for the human), a verification_uri, an expiry, and a polling interval.
  3. The CLI shows the code and URL. The user opens the URL, signs in however their organisation requires, enters the code and approves.
  4. Meanwhile the CLI polls the token endpoint with the device_code, waiting interval seconds between attempts.
  5. Once the user approves, the token endpoint returns an access token and usually a refresh token.

The recipe

# src/mytool/device_login.py
from __future__ import annotations

import time
from collections.abc import Callable
from dataclasses import dataclass

import httpx

GRANT = "urn:ietf:params:oauth:grant-type:device_code"


class LoginError(Exception):
    pass


@dataclass(frozen=True)
class DeviceCode:
    device_code: str
    user_code: str
    verification_uri: str
    verification_uri_complete: str | None
    expires_in: int
    interval: int


@dataclass(frozen=True)
class Tokens:
    access_token: str
    refresh_token: str | None
    expires_in: int | None


def start(client: httpx.Client, device_url: str, client_id: str, scope: str) -> DeviceCode:
    r = client.post(device_url, data={"client_id": client_id, "scope": scope},
                    headers={"Accept": "application/json"})
    if r.is_error:
        raise LoginError(f"could not start login ({r.status_code}): {r.text[:200]}")
    body = r.json()
    return DeviceCode(
        device_code=body["device_code"],
        user_code=body["user_code"],
        verification_uri=body["verification_uri"],
        verification_uri_complete=body.get("verification_uri_complete"),
        expires_in=int(body.get("expires_in", 900)),
        interval=int(body.get("interval", 5)),
    )


def poll(client: httpx.Client, token_url: str, client_id: str, code: DeviceCode, *,
         sleep: Callable[[float], None] = time.sleep,
         clock: Callable[[], float] = time.monotonic) -> Tokens:
    deadline = clock() + code.expires_in
    interval = code.interval
    while clock() < deadline:
        sleep(interval)
        r = client.post(token_url, headers={"Accept": "application/json"}, data={
            "grant_type": GRANT, "device_code": code.device_code, "client_id": client_id,
        })
        body = r.json()
        if r.is_success and "access_token" in body:
            return Tokens(body["access_token"], body.get("refresh_token"), body.get("expires_in"))
        error = body.get("error")
        if error == "authorization_pending":
            continue
        if error == "slow_down":
            interval += 5                      # RFC 8628 §3.5
            continue
        if error == "access_denied":
            raise LoginError("login was declined in the browser")
        if error == "expired_token":
            break
        raise LoginError(f"login failed: {error or r.status_code} {body.get('error_description', '')}")
    raise LoginError("the code expired before it was approved — run login again")

The polling loop is where most hand-written implementations go wrong, so the rules are worth stating plainly:

Responses while polling The error codes an OAuth token endpoint returns while the CLI polls during the device flow, and how the CLI should react to each. Responses while polling Response Meaning CLI does authorization_pending user has not approved yet wait interval, poll again slow_down polling too fast add 5 s to the interval access_denied user said no stop, exit non-zero expired_token code timed out stop, suggest retrying 200 + tokens approved store tokens, done These codes come from RFC 8628; handle all five and the flow never hangs.
  • Wait before each poll, including the first, and use the server's interval (default 5 seconds). Polling faster gets you slow_down and, with some providers, a temporary block.
  • On slow_down, increase the interval by five seconds and keep it increased — that is what RFC 8628 requires.
  • authorization_pending is normal, not an error; it means "keep waiting".
  • Stop on access_denied and expired_token, and on anything unrecognised, with a message that says what to do.
  • Respect the overall expiry. Use a monotonic clock so a system clock change cannot extend or cut the window.

Sleep and clock are injected, so the tests below can drive every branch instantly.

The login command

# src/mytool/cli.py
import webbrowser

import httpx
import keyring
import typer

from mytool.device_login import LoginError, poll, start

app = typer.Typer()

ISSUER = "https://login.example.com"
CLIENT_ID = "mytool-cli"
SCOPE = "openid offline_access api.read api.write"


@app.callback()
def main() -> None:
    """mytool command line."""


@app.command()
def login(no_browser: bool = typer.Option(False, "--no-browser")) -> None:
    """Sign in through your browser."""
    with httpx.Client(timeout=httpx.Timeout(15.0, connect=5.0)) as client:
        try:
            code = start(client, f"{ISSUER}/oauth/device/code", CLIENT_ID, SCOPE)
            typer.echo(f"Open {code.verification_uri} and enter the code:\n", err=True)
            typer.secho(f"    {code.user_code}\n", bold=True, err=True)
            if not no_browser and code.verification_uri_complete:
                webbrowser.open(code.verification_uri_complete)
            minutes = code.expires_in // 60
            typer.echo(f"Waiting for approval (expires in {minutes} minutes)...", err=True)
            tokens = poll(client, f"{ISSUER}/oauth/token", CLIENT_ID, code)
        except LoginError as exc:
            typer.secho(f"error: {exc}", fg="red", err=True)
            raise typer.Exit(1)
        except KeyboardInterrupt:
            typer.echo("\nlogin cancelled", err=True)
            raise typer.Exit(130)
    keyring.set_password("mytool", "access_token", tokens.access_token)
    if tokens.refresh_token:
        keyring.set_password("mytool", "refresh_token", tokens.refresh_token)
    typer.echo("Logged in. Token stored in the system keychain.", err=True)


if __name__ == "__main__":
    app()

Tokens go to the operating system's keychain rather than a file; the details, including fallbacks for headless Linux machines, are in storing tokens with keyring. Access tokens are short-lived, so other commands should refresh them using the refresh token (a normal grant_type=refresh_token POST to the token endpoint) and fall back to "run mytool login" only when refreshing fails.

UX considerations

What the user sees Terminal output of a device-flow login: a URL and a short code, a waiting message, and a confirmation once the user approves. What the user sees bash $ mytool login Open https://example.com/device and enter the code: WDJB-MJHT Waiting for approval (expires in 15 minutes)... Logged in as ana@example.com. Token stored in the system keychain. Show the code large and clearly; offer to open the browser, but never require it.
  • Make the code impossible to misread. Put it on its own line, indented and bold. Most providers generate codes without ambiguous characters; do not reformat them.
  • Offer to open the browser, never require it. verification_uri_complete pre-fills the code, which saves typing on a desktop. On SSH sessions and containers there is no browser, which is the whole point of the device flow — so always print the URL and code too, and provide --no-browser.
  • Say how long they have. "expires in 15 minutes" prevents the user wandering off and coming back to an expired code.
  • Put everything on stderr. A login command has no data output, and keeping its prompts off stdout means scripts wrapping it do not capture them.
  • Support a non-interactive path. CI cannot approve in a browser. Accept a token from an environment variable (MYTOOL_TOKEN) so pipelines never need login at all.
  • Handle Ctrl+C gracefully. Users abandon logins all the time. Exit 130 with a short message rather than a KeyboardInterrupt traceback.

Testing the behaviour

Script the token endpoint's responses with httpx.MockTransport and inject a fake sleep and clock. Each branch of the polling loop gets a test, and none of them waits:

# tests/test_device_login.py
import httpx
import pytest

from mytool.device_login import DeviceCode, LoginError, poll

CODE = DeviceCode("dev-123", "WDJB-MJHT", "https://login.test/device", None, 900, 5)


def token_endpoint(*bodies):
    it = iter(bodies)

    def handler(request):
        status, body = next(it)
        assert b"device_code=dev-123" in request.content
        return httpx.Response(status, json=body)

    return httpx.Client(transport=httpx.MockTransport(handler))


class FakeClock:
    def __init__(self):
        self.now = 0.0
        self.slept = []

    def sleep(self, s):
        self.slept.append(s)
        self.now += s

    def __call__(self):
        return self.now


def test_pending_then_success():
    client = token_endpoint(
        (400, {"error": "authorization_pending"}),
        (200, {"access_token": "at", "refresh_token": "rt", "expires_in": 3600}),
    )
    clock = FakeClock()
    tokens = poll(client, "https://login.test/token", "cli", CODE, sleep=clock.sleep, clock=clock)
    assert tokens.access_token == "at"
    assert clock.slept == [5, 5]


def test_slow_down_increases_interval():
    client = token_endpoint(
        (400, {"error": "slow_down"}),
        (400, {"error": "authorization_pending"}),
        (200, {"access_token": "at"}),
    )
    clock = FakeClock()
    poll(client, "https://login.test/token", "cli", CODE, sleep=clock.sleep, clock=clock)
    assert clock.slept == [5, 10, 10]


def test_denied():
    client = token_endpoint((400, {"error": "access_denied"}))
    clock = FakeClock()
    with pytest.raises(LoginError, match="declined"):
        poll(client, "https://login.test/token", "cli", CODE, sleep=clock.sleep, clock=clock)


def test_expiry_stops_polling():
    short = DeviceCode("dev-123", "X", "u", None, 12, 5)
    client = token_endpoint(*[(400, {"error": "authorization_pending"})] * 10)
    clock = FakeClock()
    with pytest.raises(LoginError, match="expired"):
        poll(client, "https://login.test/token", "cli", short, sleep=clock.sleep, clock=clock)
    assert len(clock.slept) == 3

The slow_down test pins the RFC's requirement that the interval stays increased, and the expiry test proves the loop cannot poll forever. For the command itself, patch start and poll and assert on what reaches the keychain; keyring supports an in-memory backend for exactly this purpose.

Conclusion

The device flow gives a CLI proper, SSO-compatible authentication for the price of two HTTP endpoints and a careful polling loop. Show the code clearly, offer but do not require a browser, poll at the server's pace and honour slow_down, handle denial and expiry explicitly, and store the resulting tokens in the keychain. Pair it with an environment-variable token for CI and your CLI works everywhere from a laptop to a headless build agent.

Frequently asked questions

Why not open a browser and listen on localhost for the redirect?

That is the authorisation code flow with PKCE and a loopback redirect, and it gives a slightly smoother experience on desktops. It fails on remote machines, containers and WSL setups where the browser cannot reach the CLI's local port. Many tools offer both and fall back to the device flow when no browser is available.

Do I need to validate the ID token?

If you only need an access token to call your API, the API validates it — the CLI just forwards it. If your CLI uses the ID token to show who is logged in, decode it for display only; do not make authorisation decisions in the client.

How should logout work?

Delete the tokens from the keychain and, if the provider supports it, call its revocation endpoint (RFC 7009) with the refresh token so it cannot be reused. Report success even if revocation fails; the local deletion is what the user asked for.

Can I use the device flow with GitHub?

Yes. Enable the device flow in your OAuth app's settings, then use https://github.com/login/device/code and https://github.com/login/oauth/access_token as the endpoints. GitHub returns form-encoded responses unless you send Accept: application/json, which the code above does.