TL;DR: CLI authentication to enterprise SSO works best when teams choose between OAuth Device Code and PKCE based on runtime context, not convenience, according to WorkOS. The broader lesson is that headless and local environments need different identity patterns, and refresh-token storage becomes the control point that matters most.
At a glance
What this is: This is a practical guide to adding enterprise SSO to CLIs with OAuth 2.0 Device Code and Authorization Code with PKCE, with the key finding that flow choice must follow runtime context.
Why it matters: IAM and identity teams need this because CLI access is increasingly part of enterprise identity scope, and the authentication pattern you choose changes phishing exposure, browser dependency, and refresh-token governance.
Context
Enterprise CLI authentication is an identity design problem, not just a developer convenience problem. Static API keys cannot satisfy enterprise SSO expectations, and terminal-based tools still need to route users through the organisation’s existing IdP and policy stack.
The core governance question is which OAuth flow fits the runtime. Local interactive use and headless use create different trust assumptions, so the right pattern for one environment can be the wrong pattern for another.
For identity programmes, the real control point moves after sign-in. Once the CLI has tokens, refresh-token handling, storage location, and revocation discipline matter more than the initial browser exchange.
Key questions
Q: How should security teams choose between Device Code and PKCE for CLI sign-in?
A: Use PKCE when the user has a local browser and the CLI can bind to a loopback redirect. Use Device Code when the environment is headless, remote, or browserless. The deciding factor is not preference but whether the runtime can preserve a browser-tied authorization path without adding unnecessary phishing or polling exposure.
Q: Why is Device Code more exposed to phishing than PKCE?
A: Device Code asks the user to type a code into a browser session, so an attacker can try to trick the user into entering a valid code after starting a parallel flow. PKCE binds the authorization response to the client that initiated the login, which removes that manual code-entry attack window.
Q: What breaks when CLI authentication relies on static API keys instead of SSO?
A: Static API keys do not inherit the organisation’s browser-based identity controls, so they bypass MFA, conditional access, and federated login policies. They also tend to behave like durable secrets rather than session-bound credentials, which makes revocation and offboarding harder to govern across multiple runtime environments.
Q: How should security teams govern refresh tokens in CLI tools?
A: Treat refresh tokens as the durable credential in the session lifecycle, store them with local protections that match the runtime, and replace them whenever rotation returns a new value. If the CLI supports multiple organisations, keep token state separated by tenant so one session cannot spill into another.
Technical breakdown
Device Code flow for headless CLI authentication
Device Code separates the secret device_code from the user-facing user_code. The CLI polls an OAuth token endpoint until the user completes sign-in in a browser on any device, which makes it workable for SSH sessions, containers, and CI-like environments without a local callback path. The trade-off is that the code typed by the user creates a phishing window, because the attacker can reuse a legitimate code if they can trick a user into entering it on the real IdP page. The protocol also requires backoff handling when the server returns slow_down, which preserves polling safety.
Practical implication: use Device Code only where a loopback redirect is unavailable, and treat the user_code entry point as a phishing-sensitive interaction.
Authorization Code with PKCE for local CLI sign-in
PKCE binds the authorization code exchange to the client that started the flow by pairing a code_verifier with a derived code_challenge. In a CLI, that usually means the tool starts a loopback HTTP listener, opens a browser, receives the code on localhost, and then exchanges it with the original verifier. This removes the manual code-entry step and closes the phishing gap created by Device Code. It also avoids the polling loop, so the auth handoff is cleaner on a user’s own machine. The browser is still the policy enforcement point, which means SSO, MFA, and conditional access continue to apply.
Practical implication: default to PKCE whenever the CLI can safely bind a local loopback port and launch a browser.
Refresh-token storage is the real control point after CLI SSO
Once the CLI receives tokens, the access token is usually short-lived and can often be treated as a transient runtime credential. The refresh token is the longer-lived asset, and it becomes the primary target if token storage is weak. That is why the storage decision matters more than the sign-in ceremony in many CLIs. A permission-restricted file is portable and works in constrained environments, while an OS keychain adds stronger local protection but introduces platform dependencies and fallback logic. Token rotation also matters, because refresh responses may replace the stored token on every use.
Practical implication: design CLI token storage around the refresh token first, then choose file-based or keychain-backed persistence based on the target environment.
Threat narrative
Attacker objective: The attacker wants valid OAuth tokens tied to enterprise CLI access so they can reuse authenticated API sessions without needing the victim’s password again.
- Entry occurs when a user is lured into entering a real device code on a legitimate IdP page after an attacker has started a parallel Device Code flow.
- Credential capture follows when the identity provider issues valid tokens to the attacker’s polling client after the victim completes authentication.
- Impact is the unauthorised collection of CLI access and refresh tokens that can be reused until revocation or expiry.
Breaches seen in the wild
- Salesloft OAuth token breach: hackers stole OAuth tokens to access Salesforce data via Salesloft.
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
CLI authentication is now part of enterprise identity governance, not a side channel. When a terminal tool can authenticate through the same IdP policies as a web app, it inherits the same access control expectations and the same governance obligations. That means identity teams need to treat CLI sign-in patterns as first-class access paths, not developer convenience features. The programme implication is that terminal access belongs in the same policy conversation as browser-based SSO.
PKCE and Device Code solve different runtime problems, not the same one. PKCE is the correct pattern when the CLI can safely anchor the flow to a local browser and loopback listener, while Device Code exists for environments where that callback path does not exist. This is not a feature preference debate. It is an environment-bound identity decision, and the wrong default either breaks usability or widens exposure. Practitioners should align auth flow selection to execution context, not team habit.
The named concept here is browser-bound terminal trust. The article shows that a CLI can safely delegate authentication to a browser session only when the flow keeps the authorization result bound to the session that initiated it. That matters because the trust boundary is no longer the terminal itself, but the linkage between terminal, browser, and IdP. The implication is that identity governance for CLIs must model that link explicitly, rather than assuming the terminal is the primary security boundary.
Refresh-token governance is the real lifecycle issue after successful SSO. Access tokens are transient, but refresh tokens are durable enough to become the practical credential lifetime question. That shifts governance from initial login assurance to post-authentication token custody, rotation, and revocation. For practitioners, the lesson is that CLI SSO is only half the control story; token persistence determines whether the sign-in event actually reduces long-lived access risk.
Enterprise SSO for CLIs validates the same principle that now applies across human, workload, and agentic identity: authentication success does not equal governance closure. Once the session exists, the remaining risk sits in token reuse, storage, and offboarding semantics. That is why identity programmes should evaluate CLI access in the same lifecycle lens used for other non-human access paths. The programme must govern the credential after issuance, not just the login at issuance time.
From our research library:
- Across one million observed logins, 1 in 4 were password-based rather than SSO, 2 in 5 were not protected by MFA and 1 in 5 used a weak, breached or reused password.
What this signals
Browser-bound terminal trust: CLI sign-in is only as strong as the binding between the terminal session, the browser session, and the IdP response. When that binding is manual, as in Device Code, the human becomes part of the attack surface. When it is loopback-bound with PKCE, the control shifts back toward the client that initiated the flow.
Identity teams should treat CLI authentication as part of the same access fabric they already govern for web SSO. That means documenting which tools use browser-based auth, which use headless auth, and which depend on long-lived refresh tokens. The operational question is not whether the CLI works, but whether its auth path is governable after deployment.
For practitioners
- Default to PKCE for interactive CLI logins Use Authorization Code with PKCE when the user has a local browser and the CLI can bind a loopback callback on the same machine. That removes the user_code entry step, eliminates polling, and keeps the browser as the policy enforcement point for SSO and MFA.
- Reserve Device Code for headless paths Use Device Code only for SSH sessions, containers, remote dev boxes, or other environments where a local browser callback is not realistic. Keep the user_code visible, never display the device_code, and implement RFC 8628 backoff handling for slow_down responses.
- Store refresh tokens as the primary credential Treat the refresh token as the long-lived asset and store it with the strongest mechanism your runtime can support, such as a permission-restricted file or an OS keychain. Rotate the stored value whenever the authentication response returns a replacement token.
- Map CLI sessions to organisation context Persist sessions by organization_id when a CLI can be used across multiple tenants, and make logout revoke the refresh token as part of offboarding. That prevents one authenticated session from becoming a reusable access path after the user switches customers or leaves the organisation.
Key takeaways
- CLI SSO is an identity design choice, not a code-snippet problem, because the authentication flow must fit the runtime the tool actually runs in.
- PKCE and Device Code address different contexts, and the wrong default can either break headless use or reintroduce a phishing window.
- After sign-in, refresh-token storage and rotation become the controls that determine whether CLI access remains bounded and revocable.
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, NIST CSF 2.0 and NIST Zero Trust (SP 800-207) set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| OWASP Non-Human Identity Top 10 | NHI-04 — Insecure Authentication | The article centers on browser-based CLI authentication choices and auth flow security. |
| NHI-07 — Long-Lived Secrets | Refresh tokens are the durable credential whose storage determines residual access risk. | |
| Recommendation — Choose an authentication flow that preserves session binding and resists code-entry abuse. Minimise refresh-token lifetime and store it with stronger local protection than the access token. | ||
| NIST SP 800-53 Rev 5 | IA-5 — Authenticator Management | Token rotation and credential lifecycle management are central to the CLI token story. |
| Recommendation — Apply IA-5 to manage token issuance, rotation, and revocation across CLI sessions. | ||
| NIST CSF 2.0 | PR.AA-05 — Access Permissions, Entitlements and Authorizations | The article maps CLI access to enterprise identity policy and authorisation decisions. |
| Recommendation — Align CLI auth paths with the same entitlement and authorisation rules used for other enterprise access. | ||
| NIST Zero Trust (SP 800-207) | 5.3 — Zero Trust Continuous Verification | Browser-bound auth and token lifecycle reinforce continuous verification over implicit trust. |
| Recommendation — Treat each CLI session as continuously verified rather than permanently trusted. | ||
Key terms
- Device Code Flow: A device code flow is an OAuth pattern for clients that cannot host a browser. The application gets a user code and polling credential, while the user completes login in a separate browser session. In CLI contexts, it shifts risk into token handling and session boundary control.
- PKCE: Proof Key for Code Exchange is a binding mechanism that links the authorization request to the later token exchange. It helps stop authorization code interception and injection by requiring proof that the same client that started the flow is the one completing it.
- Refresh Token: A longer-lived credential that can mint new access tokens without forcing the user to authenticate again. Because refresh tokens can preserve access for extended periods, they are a major governance concern when malicious or over-scoped applications are granted consent.
- Loopback Redirect: A local callback path, usually on 127.0.0.1, used by native apps and CLIs to receive an OAuth authorization code from a browser. It keeps the token exchange tied to the originating machine, which is why it is a core security property of PKCE-based CLI authentication.
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.
Published by the NHIMG editorial team on June 12, 2026.
Updated on October 8, 2026.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org