By NHI Mgmt Group Editorial TeamBased on WorkOS: “How to add auth to your Python CLI using WorkOS” (July 25, 2025)

TL;DR: Python CLI tools can authenticate users through the OAuth 2.0 Device Authorization Grant, using a browser-based approval step, periodic polling, and token exchange to avoid manual token pasting, according to WorkOS. The pattern is practical for command-line apps, but it also reinforces how device-code flows shift trust, token handling, and user verification into IAM design choices.


At a glance

What this is: This tutorial explains how to add browser-based OAuth device code login to a Python CLI and shows the polling and token exchange steps that make the flow work.

Why it matters: IAM teams should care because CLI authentication shifts user verification, token custody, and device-bound trust decisions into a pattern that must be governed like any other access path.


Context

Python CLI authentication is the practice of letting a terminal-based tool verify a user without embedding a browser in the application. In this pattern, the CLI requests a device code, the user completes approval in a browser, and the tool exchanges that approval for tokens.

The governance issue is not the code sample itself but the trust boundary it creates for IAM teams. Device code login is often the right answer for terminal apps, yet it still depends on browser-side approval, polling discipline, and token handling choices that need to fit identity policy rather than convenience alone.


Key questions

Q: How should teams implement OAuth device code login for CLI tools?

A: Use the device-code flow only for terminal or headless clients that cannot host a browser, register the app as public, and keep the browser approval step explicit. The CLI should display the user code, poll at the advised interval, and exchange the code only after user approval completes.

Q: Why does device code login change the IAM risk profile for CLI apps?

A: Because authentication no longer happens entirely inside the app. The browser, the terminal, and the token endpoint each become part of one trust chain, so user verification, token custody, and retry behaviour must all be governed as access controls rather than convenience choices.

Q: What are the signs that a CLI device code flow is being misused?

A: Look for excessive polling, repeated expired or denied authorisations, users entering codes into unexpected pages, and tokens persisting beyond the task that requested them. Those signals usually point to weak approval hygiene, poor client behaviour, or token handling that outlives the session.

Q: What is the difference between device code login and embedding a browser in a CLI?

A: Device code login keeps the terminal lightweight and moves approval into an external browser, while an embedded browser tries to contain the whole sign-in journey inside the app. For CLIs, the device-code model is usually safer operationally because it avoids shipping a browser runtime, but it still needs strong token governance.


Technical breakdown

How the OAuth 2.0 device code flow works in a CLI

The OAuth 2.0 Device Authorization Grant separates the device that needs access from the browser used for user verification. The CLI requests a device_code and user_code, displays the verification URL, and then polls the token endpoint until the browser approval is complete. The server returns tokens only after the user completes the second step, which makes the flow practical for terminal apps that cannot host a browser. The security model depends on the integrity of the code exchange, the short-lived polling window, and the user seeing the correct verification URL.

Practical implication: treat the device-code exchange as an access policy decision, not just an authentication UX pattern.

Why polling and token handling shape the risk profile

Polling is a control point, not a background detail. The interval, timeout, and handling of authorization_pending, slow_down, access_denied, and expired_token errors determine whether the CLI behaves politely or creates unnecessary load and user confusion. Once tokens are issued, the sensitive step becomes storage and use inside the CLI runtime, because access tokens and refresh tokens extend the approved session beyond the browser approval moment. For identity teams, the design question is whether the terminal app can protect those tokens at the same level expected for any other privileged client.

Practical implication: define token storage and retry behavior as part of the application’s authentication control set.

OAuth device code login in Python CLIs and user verification

Device code login is often chosen because CLIs cannot reliably embed a browser, but that convenience comes with a trust trade-off. The terminal shows the user_code and verification_uri, while the browser becomes the place where the user proves intent and completes consent. That means the correctness of the browser handoff, the visibility of the code, and the authenticity of the verification page all matter to the access decision. In practice, the control boundary shifts from the terminal to the browser-based identity experience, which must be governed consistently with the rest of the IAM stack.

Practical implication: verify that the browser approval path is protected to the same standard as any other sign-in experience.


Read and download The State of NHI & AI Agent Breach Report 2026, covering 150+ breaches impacting Non-Human Identities including AI Agents.


NHI Mgmt Group analysis

Device code login is a usability pattern, but it is also an IAM trust decision. The CLI no longer owns authentication end to end once it hands the user off to a browser for approval. That split is appropriate for terminal apps, but it means the organisation must govern a cross-device identity flow as a first-class access path, not a convenience feature.

Browser-mediated approval reduces friction, not governance responsibility. The pattern still depends on correct user_code handling, reliable polling, and token custody after issuance. If those steps are treated as implementation details, the programme ends up with an access path that is easy to use and hard to govern.

OAuth device code flow belongs in the same control conversation as other federated login patterns. The question for practitioners is not whether CLIs may use it, but whether the flow is aligned with the organisation’s expectations for session lifetime, token exposure, and approval integrity. That is where IAM design becomes operational control.

CLI authentication must be evaluated as part of workload and human identity governance together. The human approves access, the terminal holds the tokens, and the service grants API access based on that approval. Practitioners should treat that chain as one identity event with shared accountability across the user, the app, and the policy layer.

What this signals

Device-code approval creates a split identity boundary. The human authenticates in the browser, while the CLI later consumes the resulting token set. That split is acceptable only when the organisation treats code display, verification URI handling, and token storage as part of the same control plane.

The practical risk is not the grant type by itself. It is the tendency to treat terminal authentication as lightweight, even though the resulting access token can be just as sensitive as any other federated credential. IAM teams should apply the same discipline they already expect for browser SSO to terminal-based sign-in paths.


For practitioners

  • Define the CLI as a public OAuth client Register terminal tools as public applications and avoid embedding secrets that would turn the flow into a hidden credential problem. The device-code pattern assumes the app cannot keep a client secret safely.
  • Constrain token lifetime and storage Store access and refresh tokens only in the smallest feasible runtime scope and align their lifetime with the CLI’s actual session needs. A terminal tool should not keep reusable credentials longer than the task that required them.
  • Protect the verification path Make the verification URI and user code obvious to the user and ensure the browser handoff lands on an authenticated, expected identity page. The approval step is only trustworthy if the user can see where consent is happening.
  • Harden polling behaviour Honor the server-supplied interval, back off on slow_down, and stop on denial or expiration so the CLI does not behave like a noisy authentication client. Polling discipline is part of the control surface.

Key takeaways

  • OAuth device code login is a workable pattern for Python CLIs, but it moves the trust boundary into the browser approval and token exchange steps.
  • The main governance issue is not user convenience, but whether the terminal app can protect tokens and enforce the correct polling and expiry behaviour.
  • IAM teams should treat CLI authentication as a managed access path with the same scrutiny they apply to other federated sign-in flows.

Standards & Framework Alignment

This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.

OWASP API Security Top 10 addresses the attack and risk surface, while NIST SP 800-63, NIST CSF 2.0 and CIS Controls v8 set the governance and control requirements practitioners need to meet.

FrameworkControl / ReferenceRelevance
OWASP API Security Top 10API2 — Broken AuthenticationThe flow relies on secure OAuth-style authentication between CLI and authorization server.
Recommendation — Apply API2 controls to verify the CLI exchanges codes only through authenticated, expected authorization endpoints.
NIST SP 800-63SP 800-63C — FederationDevice-code login is a federated sign-in pattern that hinges on browser and token trust.
Recommendation — Use federation guidance to align terminal sign-in, browser approval, and token issuance with enterprise identity policy.
NIST CSF 2.0PR.AA-05 — Access Permissions, Entitlements and AuthorizationsThe article is about granting API access after user approval in a CLI workflow.
Recommendation — Map CLI login flows to PR.AA-05 so issued tokens reflect approved entitlements and session scope.
CIS Controls v8CIS-5 — Account ManagementThe workflow depends on managed user access and controlled token lifetimes.
Recommendation — Use account management controls to keep CLI-issued tokens tied to approved identities and intended session length.

Key terms

  • OAuth 2.0 Device Authorization Grant Flow: A login method for devices with limited input, such as TVs, printers, and command-line tools. The device asks the user to complete authentication on a separate browser, then polls for approval. Technically, it uses a device code and user code to obtain an OAuth 2.0 access token without entering credentials on the device itself.
  • Public OAuth Client: An application that cannot safely keep a client secret and therefore must be treated as externally visible in its trust model. For CLI tools, this usually means the app can initiate authorization but should not rely on hidden credentials for authentication. The security boundary shifts to scope control, token handling, and revocation.
  • Device Code Polling: The repeated checking of an authorization server until a user completes approval or the request expires. In a CLI context, polling is a control surface because the interval, timeout, and error handling influence both user experience and the risk of creating noisy or abusive authentication behaviour.
  • Token Custody: The control responsibility for where access tokens and refresh logic live, who can retrieve them, and how they are retired. In delegated integrations, token custody is often moved out of the app, but security ownership does not disappear. It shifts to the broker and the governance model around it.

Deepen your knowledge

NHI governance, agentic AI identity, and machine identity lifecycle are core topics in our NHI Foundation Level course, the industry's only accredited NHI security programme. If you are responsible for identity security strategy or NHI governance in your organisation, it is worth exploring.
NHIMG Editorial Note
Published by the NHIMG editorial team on June 8, 2026.
Updated on October 7, 2026.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org