By NHI Mgmt Group Editorial TeamBased on WorkOS: “How to add auth to your Node.js CLI using WorkOS” (July 11, 2025)

TL;DR: Browser-mediated OAuth 2.0 Device Code login can be added to a Node.js CLI, including device code issuance, user-code prompting, token polling, and handling slow_down, access_denied, and expiry conditions, according to WorkOS. The pattern improves usability for terminal tools, but it also exposes how much trust still sits in short-lived device and access tokens rather than in the CLI itself.


At a glance

What this is: This tutorial shows how to add OAuth 2.0 Device Code login to a Node.js CLI, with browser-based approval, polling, and token exchange.

Why it matters: It matters because CLI authentication shifts security decisions into token issuance, polling cadence, and user-code handling, which IAM teams must govern carefully across human and non-human workflows.


Context

OAuth 2.0 Device Code flow is a browser-mediated login pattern for terminal tools that cannot embed a web sign-in experience. The CLI asks for a device code, shows a user code and verification URL, then waits for the user to approve access in the browser before exchanging the device code for tokens.

For IAM teams, the governance question is not whether the flow works but where trust boundaries sit. The control surface moves to short-lived codes, token polling, and error handling, which means authentication design, token handling, and session limits all matter even when the application is only a command-line tool.


Key questions

Q: Where does device code login fail in practice for CLI tools?

A: It fails when teams confuse a user-friendly login prompt with a secure identity boundary. The CLI must still protect the device_code, respect the returned polling interval, and terminate cleanly on denial or expiry. If those controls are weak, the tool creates a reusable token path rather than a bounded sign-in flow.

Q: Why do OAuth device flow CLIs still need token governance?

A: Because the security value is carried by the access token, not by the terminal itself. Once a browser approves the request, the CLI can hold bearer credentials that grant API access. Governance has to cover token scope, expiry, revocation, and where the CLI is allowed to store or forward those credentials.

Q: What do security teams get wrong about polling in device code auth?

A: They often treat polling as a simple retry loop instead of a protocol-controlled exchange. The interval, slow_down response, access_denied state, and expired_token state all carry meaning. Ignoring them can produce noisy authentication traffic, failed sign-ins, and weak control over the approval window.

Q: How should IAM teams govern browser-based login for non-browser tools?

A: Treat the CLI as a registered public client with an owner, an expiry model, and a revocation path. The browser handles user authentication, but the tool still participates in the identity lifecycle through client IDs, device codes, and tokens. Governance should cover who can ship the client, how it is reviewed, and how it is retired.


Technical breakdown

How the device authorization grant works in a CLI

The device authorization grant splits authentication across two channels. The CLI requests a device_code and user_code, while the user completes authentication in a separate browser session using the verification URI. The CLI never authenticates the user directly, it only polls for completion and then exchanges the approved device_code for tokens. That architecture fits headless tools, but it also means the security property is rooted in the integrity of the authorization endpoint, the secrecy of the device_code, and the limited lifetime of the interaction. In practice, the CLI becomes a thin client for a browser-mediated identity decision.

Practical implication: Treat the device code as sensitive runtime material and constrain its lifetime, visibility, and reuse.

Why polling cadence and terminal errors matter

Polling is part of the control plane, not just a convenience loop. The CLI should poll at the interval returned by the authorization response, back off when it receives slow_down, and stop on terminal states such as access_denied or expired_token. Those responses are not edge cases. They are the protocol's way of enforcing consent, rate control, and bounded authorization windows. A CLI that ignores those signals can create noisy authentication traffic, user confusion, or unnecessary exposure to stale approval states. Reasonable timeout handling is also essential because device authorization is meant to end cleanly, not loop forever.

Practical implication: Enforce protocol-aware backoff and termination handling instead of ad hoc retry logic.

How access tokens shift trust into token governance

Once the browser approves the flow, the CLI receives access token and often refresh token material that can be used for downstream API calls. That moves the security problem from interactive sign-in to token custody, scope, and expiration. The CLI itself is still not the trusted identity, the tokens are. If token handling is weak, the same browser-mediated flow that improves usability can still produce high-value bearer material that is easy to reuse. For identity architects, the key issue is not the syntax of the grant, but how tightly the resulting tokens are bound to the session, user, and intended command boundary.

Practical implication: Design token storage, expiry, and audience scope as first-class controls for CLI authentication.


Threat narrative

Attacker objective: Obtain a valid access token that can be reused to make authenticated API calls as the approved user.

  1. Entry occurs when the CLI requests a device_code and user_code pair and exposes a verification URL for browser-based approval.
  2. Credential access occurs only after the user approves the flow and the CLI receives an access token, and possibly a refresh token, for downstream use.
  3. Impact comes from bearer token reuse, because anyone holding the issued token can call the API within its permitted scope until expiry.

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 shifts the trust boundary, it does not remove it: The browser is still the place where identity is asserted, while the CLI is only the waiting client. That means the security decision depends on the integrity of short-lived codes, the approval step, and the token exchange path. For practitioners, the important shift is to govern the handoff, not the terminal prompt.

Access review logic breaks down when the trust object is a token: Traditional review processes assume a stable account or secret can be recertified after issuance. A device-code flow creates an approval event followed by bearer tokens, so governance has to focus on issuance scope, expiry, and revocation behaviour rather than on the CLI binary itself. The implication is that command-line authentication should be treated as a token lifecycle problem.

CLI authentication now sits inside the OAuth and OpenID Connect control surface: That matters because the security properties come from protocol conformance, not developer convenience. Polling intervals, terminal error states, and token exchange semantics are part of the assurance model. Practitioners should treat device-flow implementations as identity integrations, not as simple user-experience features.

Short-lived approval windows create a narrow but real identity blast radius: The credential is only as safe as its lifetime and scope. If the token is broad or long-lived, a terminal tool can become a durable access path even when the authentication experience looks temporary. The practitioner takeaway is to align command scope, token scope, and expiry so the CLI cannot outlive the task it was meant to perform.

Browser-mediated CLI auth is an IAM pattern, not just an app pattern: Once a terminal tool depends on user_code, device_code, and access token handling, identity teams own the governance question. That includes onboarding patterns, token revocation expectations, and where approval lives in the user journey. The practical conclusion is that CLIs need the same policy discipline as any other federated application.

What this signals

Device-code CLI auth is really token governance in disguise: The user experience is about browser-based approval, but the control problem is still issuance, scope, and expiry. When teams review terminal authentication through that lens, they stop focusing on the prompt and start focusing on the lifecycle of the bearer token.

Browser mediation helps usability, but it does not change the identity model: The CLI remains a client that waits for approval, while the browser holds the trust decision. That split is useful, but only if security teams enforce tight approval windows and keep bearer credentials from becoming long-lived access paths.


For practitioners

  • Tighten device code lifetime and visibility Keep the user_code and verification_uri visible to the user, but never log or expose the device_code outside the polling process. Limit how long the approval window stays valid so uncompleted sign-ins do not remain open indefinitely.
  • Implement protocol-aware polling backoff Poll only at the interval returned by the authorization response, increase the wait when slow_down appears, and stop immediately on access_denied or expired_token. That keeps the CLI aligned with the OAuth device flow instead of inventing its own retry behaviour.
  • Bind token handling to command scope Treat the access_token and refresh_token as high-value bearer material and constrain where the CLI stores or forwards them. If the command does not need long-lived session continuity, avoid carrying refresh capability beyond the task boundary.
  • Review CLI auth as a federation design Map the terminal sign-in path to your broader OpenID Connect and OAuth controls, including user approval, token exchange, and revocation expectations. That lets IAM teams decide whether the CLI should use device code flow, a different federation pattern, or no persistent token at all.
  • Separate user-facing prompts from internal secrets Display the user_code and verification URI in the terminal, but keep the device_code internal to the polling routine. That separation reduces accidental disclosure and makes the CLI easier to audit for secret handling mistakes.

Key takeaways

  • The main security question in device-code CLI auth is not whether the login works, but how tightly the approval window and token lifecycle are controlled.
  • Browser-mediated authentication improves the user experience for terminal tools, yet the CLI still depends on bearer credentials that must be scoped and expired carefully.
  • Identity teams should treat CLI device flow as a federation pattern with governance requirements, not as a simple developer convenience feature.

Standards & Framework Alignment

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

OWASP Non-Human Identity Top 10 addresses the attack and risk surface, while NIST SP 800-53 Rev 5 and NIST CSF 2.0 set the governance and control requirements practitioners need to meet.

FrameworkControl / ReferenceRelevance
OWASP Non-Human Identity Top 10NHI-04 — Insecure AuthenticationDevice code login depends on browser-mediated authentication and token exchange.
NHI-07 — Long-Lived SecretsThe article highlights short-lived codes and bearer tokens that must not outlive the session.
Recommendation — Harden device-flow authentication boundaries and constrain token issuance to the approved user session. Enforce tight expiry and revocation rules for CLI-issued bearer tokens and device codes.
NIST SP 800-53 Rev 5IA-5 — Authenticator ManagementThe flow centres on issuing and controlling authenticators and bearer tokens.
Recommendation — Apply authenticator management controls to device codes, access tokens, and refresh tokens.
NIST CSF 2.0PR.AA-05 — Access Permissions, Entitlements and AuthorizationsCLI access depends on properly scoped approvals and token permissions.
PR.AA-01 — Identity and Access Management Policy and ProceduresThe post is about governing CLI sign-in as part of an IAM process.
Recommendation — Align CLI token scopes with least-privilege authorization boundaries. Document CLI authentication policy, approval paths, and token handling expectations.

Key terms

  • OAuth 2.0 Device Code Flow: An OAuth sign-in pattern for devices or terminals that cannot host a browser. The application requests a device code, the user completes approval in a separate browser session, and the application later exchanges that approval for tokens. In CLI contexts, the governance focus is on code secrecy, polling behaviour, and token scope.
  • Bearer Token: A bearer token is a credential that grants access to whoever possesses it, without requiring strong proof that the holder is the intended client. In NHI environments, that makes theft and replay the main risk, especially when tokens are long-lived, broadly scoped, or stored in local files.
  • Polling Interval: The wait time a client uses between repeated checks for an authentication result. In device code flow, the interval is part of protocol control, not a developer preference, because excessive polling can trigger rate control while insufficient backoff can create failed or noisy sign-in behaviour.
  • Authorization Pending: A device-flow response meaning the user has not yet completed browser approval. It is a normal interim state, not an error, and the client should keep waiting at the instructed interval rather than restart the flow or treat the request as failed.

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 building or maturing an IAM programme, it is worth exploring.
NHIMG Editorial Note
Published by the NHIMG editorial team on June 8, 2026.
Updated on October 8, 2026.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org