Skip to navigation

Claude Code Credential Precedence: API Key, Helper and OAuth

In short: Audit which credential Claude Code selects when an API key, helper script and subscription login coexist, then remove the source you did not intend.

Published 18 min read
On this page

Direct answer

Audit credential sources from the highest documented priority downward, then remove the unintended source where it is defined. Official (F026): gateway sessions outrank every other source, and cloud-provider variables come before the direct Anthropic subset. Within that subset, the order is ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY, apiKeyHelper, CLAUDE_CODE_OAUTH_TOKEN, profiles or federation credentials, then subscription OAuth. Official (F027): in interactive mode, an API key must be approved once before it overrides subscription access, so variable presence alone does not prove approval. Official (F028): ANTHROPIC_API_KEY becomes X-Api-Key, while ANTHROPIC_AUTH_TOKEN supplies a Bearer authorization value. The win is an intentional identity and request path. The loss is that a lower-priority login can look valid while remaining inactive, and the supplied evidence does not provide a safe command that prints the selected source.

Why the wrong source persists

Several credentials can coexist without producing an obvious error because a shell variable may survive from an earlier project, a settings file may define another value, a helper may still produce credentials and a subscription login may remain available below them. If the highest eligible source changes, request attribution can change even though the visible command remains claude, which is why source location matters more than the presence of a successful login screen.

That ambiguity costs debugging time because repeating browser login does not address a higher-priority environment variable, rotating a subscription session does not address helper output and deleting configuration can remove useful settings without establishing which source was active. A source inventory is therefore more useful than another round of uninstall and reinstall, provided it records names and locations without exposing the credential values themselves.

Safety depends on knowing which credential is sent because Official (F028): the API-key and auth-token variables use different request headers and are not interchangeable labels for one secret, while a copied value placed under the wrong name can change how the request is authenticated. The API key security reference and the secrets in logs and transcripts guide support careful handling, but neither replaces the documented header distinction.

Evidence map placing gateway and cloud sources above the direct API-key, helper and OAuth credential order
Evidence map based on official authentication fact F026. Gateway and cloud-provider sources remain above the direct Anthropic subset; interactive API-key approval is a separate condition from F027.

List the credentials present

Begin with names and locations, not values. Check the launch environment for ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY and CLAUDE_CODE_OAUTH_TOKEN. Check effective settings for an apiKeyHelper entry without displaying any credential the helper generates. Note whether profiles or federation credentials are part of the approved setup. Record whether a gateway session or cloud-provider configuration is present, because both sit above the direct subset in F026.

A shell-only inventory can miss values supplied elsewhere. Settings-file environment entries and process startup behavior have their own timing rules. Official (F034): shell variables are read at startup, while settings-file env entries apply to running sessions unless a feature reads its variable only at startup. Recheck after changing the launch environment instead of assuming an already running process reflects the edit. An inventory becomes useful when each source is tied to the process that can supply it, because a name marked set in one shell says nothing about a helper entry, an IDE launch or a gateway session running under another context.

Use the settings env and process replacement runbook when a shell value and a settings entry disagree. Use the settings precedence runbook to locate the scope that supplies a key. Those configuration questions are related to, but distinct from, the credential order in F026.

Status-only environment inspection

This Bash example reports only whether selected names are set. It redirects each value away from the terminal and never prints credential material. It is a Derived diagnostic procedure from F026, not official Claude Code output.

for name in ANTHROPIC_AUTH_TOKEN ANTHROPIC_API_KEY CLAUDE_CODE_OAUTH_TOKEN; do
  if printenv "$name" >/dev/null; then
    printf '%s=set\n' "$name"
  else
    printf '%s=unset\n' "$name"
  fi
done

A set result establishes presence, not validity, approval or selection. An unset result applies to the process in which the check runs. It does not prove that another shell, IDE, settings file or service lacks the variable. Compare the launch context before drawing a conclusion.

Do not extend this example into a full environment dump. Other variables may contain secrets or unrelated provider configuration. The GitHub Actions secrets guide provides adjacent guidance for keeping credentials out of logs, while the WSL IDE environment guide explains why different launch surfaces can inherit different values.

Read the documented precedence order

F026 contains two layers because gateway sessions outrank all other sources while cloud-provider variables appear before the direct Anthropic credential subset, and only after those exceptions does the direct order begin with ANTHROPIC_AUTH_TOKEN and continue through the remaining sources. A troubleshooting checklist that starts with ANTHROPIC_API_KEY and ignores the exceptions can therefore identify the wrong override, even when its direct-subset ordering is otherwise correct.

Within the direct subset, ANTHROPIC_AUTH_TOKEN comes first. ANTHROPIC_API_KEY follows. After that comes apiKeyHelper, then CLAUDE_CODE_OAUTH_TOKEN. Profiles or federation credentials come next, and subscription OAuth is last in this documented subset. Preserve that sequence when reviewing a machine with several possible sources.

Credential source versus documented priority

Priority layer Source What to inspect Important caveat
Above all others Gateway session Whether a gateway session is active in this launch context Do not start with direct variables if this layer is present
Above the direct subset Cloud-provider variables Whether an approved cloud-provider configuration is present This article does not configure a cloud provider
Direct subset, first ANTHROPIC_AUTH_TOKEN Name and definition location Sends a Bearer authorization value under F028
Direct subset, second ANTHROPIC_API_KEY Name, definition location and interactive approval state Presence alone does not prove approval
Direct subset, third apiKeyHelper Effective helper configuration Helper output outranks the OAuth token below it
Direct subset, fourth CLAUDE_CODE_OAUTH_TOKEN Name and definition location Lower than helper output
Direct subset, fifth Profiles or federation credentials Approved profile or federation context Keep provider setup outside this guide
Direct subset, last Subscription OAuth Intended subscription sign-in A successful login can remain inactive under a higher source

Official (F026): the table preserves the documented order and its exceptions. It does not claim that every machine has every source, nor that a present source is valid for a particular request.

Account for gateway and cloud-provider exceptions

Check gateway context before editing direct credentials. Official (F026): gateway sessions outrank all other sources. If a gateway session is active, removing ANTHROPIC_API_KEY may not change the source used by that session. Record the gateway context and consult its owner before changing direct credential variables.

Cloud-provider variables also come before the direct subset. Their presence can make a local API-key audit misleading. This article intentionally stops at identification. It does not provide Bedrock, Vertex or other provider setup, and it does not suggest replacing a managed provider credential with a personal key.

The custom API base URL resource explains route configuration, while the corporate proxy, TLS and mTLS guide covers a separate network boundary. Neither route changes F026. Keep endpoint, network and credential-source questions distinct so one successful connection is not treated as proof of all three.

When a managed environment supplies credentials, compare the intended policy with the observed source inventory. Do not remove an organization-managed value merely to make a personal subscription active. Escalate the mismatch to the configuration owner with names and locations only. That approach preserves the managed boundary and avoids printing secrets in the escalation.

Credential-audit workflow from source inventory through gateway exceptions, approval state and source-specific removal
Workflow derived from official facts F026 through F028. It audits higher-priority exceptions before direct credentials and keeps values out of the evidence record.

Check interactive API-key approval

ANTHROPIC_API_KEY has an additional condition in interactive mode. Official (F027): an API key must be approved once before it overrides subscription access. Do not infer approval from the variable being set. A status-only environment check cannot answer the approval question, and a previous approval should not be assumed for a different launch context.

Review the interactive approval step when an API key is intended to override subscription access. Follow the client’s prompt rather than copying approval text from another setup. If the key is not intended, remove the unintended source instead of approving it simply to clear a warning. Approval changes which source can take precedence; it is not a general repair for every authentication error.

The browser login and logout runbook explains the interactive sign-in state transition. It does not replace this approval check. Similarly, the OS credential-storage reference maps storage locations but does not establish which source has priority.

Approval-state decision table

Observation Supported conclusion Next safe action
API-key variable is set The name is present in that process Check approval separately
Interactive key approval was completed once F027’s approval condition may be satisfied for that context Continue the precedence audit
Subscription login succeeds Subscription OAuth is available Check higher-priority sources before expecting it to be active
API key is unintended It may override subscription after approval Remove its definition at the source
Approval state is unknown No selection conclusion is justified Inspect the interactive flow without printing values

Official (F027): approval is a one-time interactive step before override. Unknown: the fact pack does not specify a command that reports approval state or a universal recovery procedure when approval is interrupted. Approval evidence should stay separate from variable-presence evidence, because a status-only check can establish that ANTHROPIC_API_KEY exists while remaining unable to show whether the interactive condition for subscription override has been satisfied.

Compare API-key and auth-token headers

The two direct variables have different meanings. Official (F028): ANTHROPIC_API_KEY is sent as X-Api-Key, while ANTHROPIC_AUTH_TOKEN supplies a Bearer authorization value. A migration that renames one variable to the other without checking the credential type can therefore preserve the secret value while changing its request semantics.

Record the intended authentication style before editing. If the credential was issued as an API key, do not relabel it as an auth token merely because both appear in the precedence list. If an auth token is intended, do not place it under the API-key name to make a template compile. The header distinction in F028 is the relevant official evidence.

The Anthropic Messages format guide explains message-format compatibility, while the OpenAI versus Anthropic API comparison explains the broader format boundary. Neither makes the two Claude Code variables interchangeable. Format compatibility and credential naming are separate checks.

Credential type versus request header

Variable Documented request use Incorrect assumption to avoid
ANTHROPIC_API_KEY X-Api-Key Any variable containing a secret is equivalent
ANTHROPIC_AUTH_TOKEN Bearer authorization value Renaming an API key preserves its meaning
CLAUDE_CODE_OAUTH_TOKEN Separate OAuth credential source in the order It outranks apiKeyHelper
Helper-generated credential Higher than CLAUDE_CODE_OAUTH_TOKEN in F026 Its presence is visible in a shell variable check

Official (F026, F028): priority and header behavior are separate properties. Audit both when changing a credential definition.

Place apiKeyHelper in the ladder

apiKeyHelper sits above CLAUDE_CODE_OAUTH_TOKEN, profiles or federation credentials and subscription OAuth in the direct subset. Official (F026): that position matters when a helper still runs after a user switches to a subscription login. The subscription can authenticate successfully while the helper remains the selected source.

Inspect effective settings to determine whether a helper is configured and which scope supplies it. Do not execute a helper merely to display its output during an audit. The settings precedence runbook helps locate the controlling scope, and the settings-file secret exposure guide explains why moving generated credentials into convenient files can widen exposure.

The separate apiKeyHelper refresh runbook covers helper timing and failures. This article stays on selection order. A refreshed value does not move the helper above ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY, because F026 fixes its place in the order.

Profiles and federation credentials also remain part of the documented sequence. Identify their presence without opening a provider tutorial. If they are managed, ask the owner before removal. Subscription OAuth is lower in this subset, so it should be treated as the fallback source to verify rather than the automatic explanation for every active request.

Remove the unintended higher-priority source

Name the source before changing it. For an environment variable, locate the launch configuration that defines it. For a settings entry, identify the effective settings scope. For a helper, identify the configuration that invokes it. For a gateway or cloud-provider source, involve the owner of that managed context. This source-specific approach is more precise than clearing every credential until something changes. Source-specific removal also preserves unrelated identity configuration, because deleting a higher-priority definition does not require destroying lower-priority settings, allowed tools or history that may still be needed after the intended credential becomes active in the same launch context.

Official (F034): shell variables are read at startup. After editing a shell launch definition, start a fresh session and repeat the status-only inventory. For settings-file changes, remember that some features read their variable only at startup. Relaunch when the feature is startup-sensitive instead of claiming every edit applies immediately.

Do not remove an entire configuration directory to eliminate one override. Official (F022): deleting ~/.claude removes settings, allowed tools, MCP server configurations and session history. That is a much broader action than removing an unintended credential source. The uninstall and retention runbook explains why configuration deletion requires a separate decision.

Derived scenario matrix

Sources present, with higher exceptions absent Documented direct-subset result Practical check
Auth token plus API key Auth token has higher priority Inspect the auth-token definition first
API key plus helper API key has higher priority, subject to interactive approval Check approval before concluding
Helper plus OAuth token Helper has higher priority Inspect effective helper configuration
OAuth token plus subscription OAuth CLAUDE_CODE_OAUTH_TOKEN has higher priority Inspect the explicit token definition
Profile or federation credential plus subscription OAuth Profile or federation credential has higher priority Confirm the approved profile context
Gateway session plus any direct source Gateway session outranks all of them Review the gateway context before direct edits

Derived from F026 and F027: each row assumes the listed sources are present and eligible in the same launch context. Real selection can be affected by the higher gateway and cloud-provider layers, which the matrix deliberately excludes.

Verify the intended identity is active

Repeat the inventory after the change, then compare it with the intended source. Confirm that the unwanted definition is gone from the process and from the launch configuration that supplies it. Start a fresh session where startup timing applies. Do not use a printed token as proof; names, locations and observed account context are sufficient for the audit record. Verification should preserve the distinction between source presence and source selection, because a process can contain several eligible definitions while the documented order determines which one takes priority for the request.

Next, perform a nonsecret verification through the normal approved client flow. Observe the account or organization context shown by the client and the result of an ordinary request. The fact pack does not define a command that prints the selected credential source, so do not invent one. A successful request alone also does not prove which source was used; combine it with the source inventory and intended identity.

If behavior still disagrees with the inventory, revisit gateway and cloud-provider exceptions before repeating direct edits. The usage tracking reference can provide broader attribution context, but it is not a substitute for the documented precedence order. Record unresolved differences as unknown rather than asserting a defect.

Tradeoff diagram showing that removing a higher-priority credential can restore subscription use while changing request attribution
Tradeoff derived from official facts F026 through F028. Source removal can change the active identity and header behavior; the sources do not quantify cost or success rates.

Verification record

Check Pass condition Evidence to retain
Higher exceptions reviewed Gateway and cloud-provider context is known Names and owner, no values
Direct order reviewed Every present source is placed using F026 Source inventory
API-key approval checked Approval state is not inferred from presence Interactive step completed or marked unknown
Unwanted source removed Definition is absent at its origin File or launch-configuration location
Fresh context checked New process reflects the intended inventory Status-only set or unset results
Identity observed Account context matches the intended source Redacted observation

Honest loss and data gaps

The concrete win is a request path with an identified credential source and a documented reason for its priority. The concrete loss is that subscription OAuth can remain available yet inactive beneath a higher source, and the two direct variables use different headers. The practical implication is to remove the specific unintended definition rather than resetting all identity state.

Unknown: F026 through F028 do not provide a safe selected-source display command, a universal approval-state query or a measured frequency of override mistakes. No community report is used here to claim a precedence defect. Troubleshooting and CLI reference pages are linked official sources in the register, not independently fetched evidence for extra output fields or recovery commands.

A future update should add a selected-source inspection method only if current official documentation verifies it. Until then, keep the audit based on names, locations, approval state and observed identity. The settings validation runbook can help inspect rejected settings entries, but it should not be described as a credential-precedence reporter. Future evidence should also preserve the gateway and cloud-provider exceptions, because a direct-subset diagram without those higher layers would simplify the documented order in a way that sends readers back to the wrong override during troubleshooting.

Control checklist for gateway exceptions, direct credential order, API-key approval and value-free verification
Checklist based on official facts F026 through F028 and startup timing fact F034. It supports a source-specific audit without exposing values or inventing selection output.

Adjacent batch runbooks

Related setup question Batch runbook
Which binary is running? Verify native PATH and binary ownership
Who owns a Homebrew install? Manage Homebrew cask updates manually
Is WinGet the installation owner? Locate the WinGet binary and maintain PATH
Was npm used globally? Check Node and the npm global prefix
Does a Linux package own the CLI? Compare apt, dnf and apk operations
Could an update change be relevant? Choose an update channel and downgrade floor
Should removal preserve configuration? Uninstall while deciding configuration retention
How does a fresh browser login work? Complete browser login and understand logout
Where are credentials stored? Compare macOS, Linux and Windows credential paths
Was the configuration root moved? Set an absolute CLAUDE_CONFIG_DIR
Must an organization be pinned? Restrict SSO organization and login method
Why does helper timing matter? Audit apiKeyHelper refresh timing
Verdict showing source-specific credential removal after gateway exceptions, direct order and API-key approval checks
Verdict based on official facts F026 through F028. The audit can identify definitions and priority, but the sources do not provide a universal selected-source display command.

One AI option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so One AI is not a drop-in credential source for the precedence ladder above. One AI’s active offer is for OpenAI-format agents using https://api.oneaiapikey.com/v1, one key and 46 live free IDs. Its Claude IDs were unavailable on 2026-11-27. Do not treat those free IDs as Claude Code credentials or place them in ANTHROPIC_API_KEY. For a separate OpenAI-format agent, review the free model route and the OpenAI-format quickstart. Keep Claude Code credentials in their documented sources.

FAQ

Does ANTHROPIC_API_KEY always beat subscription OAuth?

Not without checking the documented conditions. Official (F026): gateway and cloud-provider sources come first, and ANTHROPIC_AUTH_TOKEN precedes the API key in the direct subset. Official (F027): interactive API-key approval is required before the key overrides subscription access.

Can I swap ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN because both contain secrets?

No. Official (F028): the API key is sent as X-Api-Key, while the auth token supplies a Bearer authorization value. Their request behavior differs.

Why is apiKeyHelper still active after I sign in with a subscription?

Official (F026): helper output has higher priority than CLAUDE_CODE_OAUTH_TOKEN, profiles or federation credentials and subscription OAuth. Inspect the effective helper configuration before repeating login.

How can I check variables without exposing their values?

Use a status-only check that reports set or unset and redirects values away from the terminal. Presence still does not prove approval, validity or selection. Review higher-priority exceptions separately.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →