Skip to content

Frequent re-authentication required with multiple concurrent Claude Code sessions (OAuth refresh token race condition) #24317

Closed

Description

@pfallonjensen

Bug: Frequent re-authentication required with multiple concurrent Claude Code sessions

Description

Claude Code requires re-authentication (browser OAuth flow) multiple times per day, even though a valid refresh token exists in ~/.claude/.credentials.json. This appears to be caused by a race condition when multiple concurrent Claude Code sessions attempt to refresh the same OAuth token.

Environment

  • Claude Code version: 2.1.37
  • OS: macOS 15.7.1 (Apple Silicon, arm64)
  • Subscription: Team (Max 5x tier)
  • Concurrent sessions: 7-12 active Claude Code processes at any given time

Steps to Reproduce

  1. Open 5+ terminal tabs, each running claude in different project directories
  2. Work normally across sessions throughout the day
  3. After some time (typically a few hours), one or more sessions will prompt: /login to re-authenticate
  4. Re-authenticating in one session may cause other sessions to lose their auth shortly after

Expected Behavior

The refresh token should silently renew the access token without user interaction. Multiple concurrent sessions sharing the same credentials file should coordinate token refresh (e.g., file-based locking, or re-reading the credentials file before attempting refresh).

Actual Behavior

Sessions frequently lose authentication and require a full browser-based OAuth re-login. This happens multiple times per day with several concurrent sessions open.

Root Cause Analysis

The credentials file (~/.claude/.credentials.json) contains:

  • accessToken — short-lived (~15 hour expiry)
  • refreshToken — used to obtain new access tokens

OAuth refresh tokens are typically single-use: when one process uses the refresh token to get a new access/refresh token pair, the old refresh token is invalidated server-side. With N concurrent Claude Code processes:

  1. Process A's access token expires
  2. Process A uses the refresh token → gets new access token + new refresh token
  3. Process A writes new credentials to ~/.claude/.credentials.json
  4. Process B's access token also expires (or was already expired)
  5. Process B tries to use the old refresh token (which it read into memory at startup)
  6. Server rejects the old refresh token (already consumed by Process A)
  7. Process B prompts user to re-authenticate via browser

This race becomes increasingly likely with more concurrent sessions, as the window for token expiry overlap grows.

Impact

  • Disrupts workflow — interrupts active coding sessions to complete browser OAuth flow
  • Blocks headless/SSH use cases entirely — Claude Code cannot be used over SSH when re-auth is needed, because the OAuth flow opens a browser on the host machine. This makes remote access (e.g., from a mobile SSH client) unreliable.
  • Scales with usage — power users who keep multiple sessions open (different projects, different terminal tabs) are most affected

Suggested Fixes

  1. Re-read credentials from disk before refresh: Before attempting a token refresh, check if another process has already written a fresh token to the credentials file. If the file's expiresAt is in the future, use the new token instead of refreshing.

  2. File-based locking on refresh: Use a lockfile (~/.claude/.credentials.lock) to prevent concurrent refresh attempts. Only one process refreshes at a time; others wait and then read the refreshed token.

  3. Longer-lived refresh tokens: If the refresh token had a longer lifetime or was multi-use (not invalidated on first use), concurrent sessions could independently refresh without invalidating each other.

  4. In-memory token sharing: Use a local IPC mechanism (Unix socket, shared memory) so all Claude Code processes share a single token manager that handles refresh.

Workaround

Currently, the only workaround is to close stale Claude Code sessions to reduce the number of concurrent processes competing for token refresh. This is not ideal for users who work across multiple projects simultaneously.

An ANTHROPIC_API_KEY environment variable bypasses OAuth entirely but uses API billing instead of the subscription — not a real fix for subscription users.

Additional Context

This bug is particularly impactful for users building automation around Claude Code (e.g., LaunchAgent-triggered sessions, SSH-based remote access from mobile devices) where browser-based re-authentication is impossible.

Activity

  1. added
    bug
    has repro
    platform:macos
    on Feb 9, 2026
  2. github-actions commented on Feb 9, 2026

    @github-actions

    Found 3 possible duplicate issues:

    1. [Bug] OAuth refresh token race condition in multi-instance scenarios #22600
    2. Bug: Multi-Session Hang - Only Latest CLI Session Works (WSL2 + OAuth) #13448
    3. claude code corrupts ~/.claude.json on mac while running 5 concurrent sessions #3117

    This issue will be automatically closed as a duplicate in 3 days.

    • If your issue is a duplicate, please close it and 👍 the existing issue instead
    • To prevent auto-closure, add a comment or 👎 this comment

    🤖 Generated with Claude Code

  3. mieubrisse commented on Feb 10, 2026

    @mieubrisse

    I'm hitting exactly this issue. Thank you for the forensics!

  4. schoukah commented on Feb 20, 2026

    @schoukah

    Same issue here. Thank you for documenting it.

  5. sasha-computer commented on Feb 21, 2026

    @sasha-computer

    This is a frustrating issue, I have the exact same issue.

  6. mieubrisse commented on Feb 21, 2026

    @mieubrisse

    I worked around this using claude setup-token and then feeding it in as the CLAUDE_CODE_OAUTH_TOKEN environment variable. It skips all the "OAuth tokens invalidating each other", but has the downside that it doesn't allow /usage

  7. mieubrisse commented on Feb 23, 2026

    @mieubrisse

    Has anyone tested with v2.1.44? Supposedly:

    Fixed auth refresh errors

  8. sstklen commented on Feb 24, 2026

    @sstklen

    Hey! I ran into a similar pattern in our bug knowledge base and thought this might help.

    What's happening: Token-scope regression: (1) operator.admin did not satisfy operator.* wildcard scope checks in device-auth, causing repeated pairing/auth churn on every CLI invocation. (2) Pairing approval flow omitting scopes field would rotate tokens to empty scope sets, effectively wiping device-auth.json tokens back to {} on each command.

    What worked for us:

    Two fixes: (1) Make operator.admin satisfy operator.* wildcard scope checks so admin-scoped devices don't trigger re-pairing. (2) Prevent pairing approvals that omit scopes from rotating tokens to empty scope sets — preserve the approved scope baseline for existing device tokens.

    Steps:

    1. In device-auth scope checking logic, implement proper wildcard matching so operator.admin satisfies operator.* checks (commit 55d492b4c)
    2. In pairing approval handler, guard against missing `scopes
    // Fix 1: Wildcard scope matching (scope-check.ts)
    // Before: exact match only
    // if (requiredScope === deviceScope) return true;
    // After: support wildcard matching
    function scopeSatisfies(deviceScope: string, requiredScope: string): boolean {
      if (deviceScope === requiredScope) return true;
      // operator.admin satisfies operator.*
      const [dNs, dPerm] = deviceScope.split('.');
      const [rNs, rPerm] = requiredScope.split('.');
      if (dNs === rNs && rPerm === '*') return true;
      return false;
    }
    
    // Fix 2: Prevent empty-scope rotation (pairing-approval.ts)
    // Before: unconditionally rotated token with new scopes
    // device.token = rotateToken(device, approval.scopes);
    // After: preserve existing scopes if approval omits them
    if (approval.scopes && approval.scopes.length > 0) {
      device.token = rotateToken(device, approval.scopes);
    } else {
      // Preserve existing approved scope baseline, do not rotate
      device.token = refreshToken(device, device.scopes);
    }

    Hope this helps! Let me know if it doesn't match your case — happy to dig deeper. 🦞

    Disclosure: This analysis is from Confucius Debug, an AI-powered community KB for agent bugs. Please verify before applying.


    🦞 Confucius Debug — community knowledge base for AI agent bugs. Free to search via MCP.

  9. garimto81 commented on Feb 27, 2026

    @garimto81

    Reproducing with 8 concurrent VS Code sessions on Windows

    Environment:

    • OS: Windows 11 Enterprise
    • Claude Code: v2.1.62
    • Subscription: Max (20x tier)
    • Setup: Up to 8 VS Code windows, each running its own Claude Code session simultaneously

    Symptoms:

    • Every time a new VS Code window launches Claude Code, a browser OAuth login popup appears
    • Previously (older CLI versions), a single login persisted across all sessions
    • The issue is consistent and reproducible — not intermittent

    Impact:

    • With 8 concurrent sessions, the re-authentication friction is severe
    • Breaks the multi-project workflow where each VS Code window targets a different repository
    • Sometimes re-authentication is required even mid-session when another window triggers a token refresh

    Analysis:
    All 8 processes share ~/.claude/.credentials.json. When one process refreshes the single-use OAuth token, the remaining 7 processes hold an invalidated refresh token and must re-authenticate via browser.

    A file-level lock or credentials re-read before refresh (as suggested in this issue) would resolve this for multi-window VS Code workflows.

  10. unwashedlugosi commented on Mar 3, 2026

    @unwashedlugosi

    I'm hitting this constantly on macOS. I run 2-3 concurrent Claude Code sessions via Remote Control and get logged out multiple times per day — sometimes within minutes of logging back in.

    Version 2.1.63, macOS 15.4, Max plan.

    The multi-session race condition described here matches my experience exactly. Happy to provide logs or other details if helpful.

  11. golproductions commented on Mar 12, 2026

    @golproductions

    Damn, okay... I see exactly what's going on here. It's frustrating, but the real reason this is happening is a perfect storm of modern OAuth 2.0 security practices colliding with your multi-session power-user setup. Specifically, those refresh tokens are one-time-use, meaning the moment Process A uses the current refresh token to get new credentials and a new refresh token, the old refresh token (which Process B and all your other tabs are still holding in memory) is instantly made useless by the auth server.
    Here's the engineering physics: when multiple sessions are running, they all read the credentials at startup. Let's say session 1, 2, and 3 all have the same initial refresh token, R0. Then session 1's access token expires. It presents R0, gets a fresh access token, and gets R1 (a new refresh token). It writes this back to disk. Then session 2 or 3, both still holding R0 in memory, eventually expire their access tokens and present the (now revoked) R0. The server rejects it, assumes someone stole it, and makes you log in from scratch in a browser.
    To win next time, you must implement atomic, coordinated access to the token storage. I'm talking about implementing file locking (using something like fcntl in Python, or equivalent mechanism for Claude Code's language) around the entire refresh flow. Your sessions need to coordinate:
    A session wanting to refresh must first acquire a system-wide lock (e.g., on a credentials.lock file). This ensures mutual exclusion.
    Before it even considers refreshing, it must read the credentials file again. It needs to check if another session already refreshed the token. If the token on disk is already fresh (i.e., its expiresAt is in the future), the current session should just use that new token and not refresh.
    If the token on disk is still expired, then it proceeds to call the OAuth server, gets the new token pair, and writes it to disk.
    Only after writing to disk does it release the lock.
    This makes the refresh process atomic and serializes all requests. Your concurrent sessions will effectively wait in line, and the first one in line does the work while the others just reap the benefits. It's the only way to avoid that race condition when dealing with single-use refresh tokens.

    • Introducing GOL V1.1
  12. kokuyouwind commented on Mar 14, 2026

    @kokuyouwind

    I've been hitting this same issue and wanted to share additional context that might be useful.

    As a workaround, I had been using the CLAUDE_CODE_OAUTH_TOKEN approach mentioned in this thread — exporting a token via claude setup-token so each concurrent session could start with a pre-authenticated state, bypassing the browser re-auth loop entirely. This worked reliably until the server-side enforcement in February 2026 blocked OAuth tokens from being used outside the official Claude Code interactive flow.

    I understand the policy reasoning, but the effect for legitimate multi-session users is that the only practical workaround for this bug is now gone. The recent CHANGELOG entries mention fixes for "a race condition where stale OAuth tokens could be read from the keychain cache during concurrent token refresh attempts" — but the underlying issue of sessions losing auth when running multiple concurrent instances still persists in practice.

    For users running several terminal sessions across different projects simultaneously, there's currently no stable path that stays within the subscription. Switching to ANTHROPIC_API_KEY works technically but moves to per-token API billing, which defeats the purpose of a Max/Pro plan.

    A proper fix (file lock, IPC token sharing, or similar) would be the right solution. Alternatively, an officially supported way to pre-authenticate concurrent sessions within the subscription scope would address both this bug and the use case that CLAUDE_CODE_OAUTH_TOKEN was filling.

  13. 11 remaining items

  14. chid commented on May 9, 2026

    @chid

    Is this fixed? Is the expected behaviour that Claude is meant for single active session?

  15. Houtamelo commented on May 12, 2026

    @Houtamelo

    Could this issue be re-opened? It is certainly not fixed as many others have pointed out.

  16. Alandougherty commented on May 28, 2026

    @Alandougherty

    I ran into this same problem over mosh and built a small workaround: a LaunchAgent that refreshes ~/.claude/.credentials.json from the refresh token, bypassing the keychain. Published it here in case it helps anyone:

    https://github.com/Alandougherty/claude-code-headless-macos

  17. added a commit that references this issue on Jul 3, 2026
  18. vdavid commented on Jul 17, 2026

    @vdavid

    Claude solved it for me by going through its binary (v2.1.211).

    The solution: add CLAUDE_CODE_OAUTH_401_WAIT_MS=60000 to ~/.zshenv.local. It gives each Claude instance a 60-second window to notice the session refresh. It has worked for me for 24+ hours. Before this, it kept logging me out when I ran my 10+ parallel sessions.

    If you're interested in more, here it is, in Claude's words:


    This is the answer. I found the actual mechanism.

    First, #24317's status

    Closed as COMPLETED on 2026-05-07 — with no maintainer explanation. Users pushed back immediately after ("It is certainly not fixed as many others have pointed out"), and there's no open successor issue. So officially "done," practically not. Your mid-June onset sits after that close.

    What actually happened (from the binary)

    Claude Code does have a recovery mechanism for exactly your race. When a session gets a 401 because another session rotated the token, there's a function that polls the credential store every 2s, waiting for the token to change — and if it sees a new one, it recovers and continues instead of logging out:

    while (Date.now() < deadline) {
      let s = readToken();
      if (s && s !== failedAccessToken) return true;   // someone else refreshed → recover
      await sleep(2000);
    }

    And here's the kicker — the timeout that drives it:

    function fFh() {
      let e = env.CLAUDE_CODE_OAUTH_401_WAIT_MS;
      if (e !== void 0) return e;
      return env.CLAUDE_CODE_REMOTE_SESSION_ID ? 60000 : 0;   // ← 60s remote, 0 LOCAL
    }

    The recovery defaults to 60 seconds for remote sessions and 0 — disabled — for local ones. Your 10 instances are local. So when one rotates the token, the others get a 401, wait zero milliseconds, and log out immediately. The fix Anthropic shipped (and closed #24317 on) exists — it's just off by default for exactly your case.

    The fix

    export CLAUDE_CODE_OAUTH_401_WAIT_MS=60000
    

    That gives each instance a 60-second window to notice the winner's refresh and carry on. It's the same value Anthropic themselves chose for multi-session remote use. Crucially: it's a timeout number, not an auth source — it won't trip the api_key_precedence gate, so your connectors stay working. No tension this time, and you keep all 10+ instances.

    Honest caveats: it's undocumented and not part of any public contract (like the client_id caveat on that other repo), so a future version could change it. I've read the code path carefully but can't empirically prove it end-to-end without waiting out a real 8h expiry — the proof is the next couple of days. Worst case if the token is genuinely dead, a session pauses up to 60s before telling you to /login, which still beats an instant cascade.

    On Claude Desktop: with this set it matters much less, but it's still one fewer racer — uninstall it if you don't use it, no downside.

    Want me to add CLAUDE_CODE_OAUTH_401_WAIT_MS=60000 to ~/.zshenv.local (right where we removed the other token)? Then you just need a fresh shell, and we watch whether the 8h drop stops.


    Hope it helps y'all too!

  19. kynbeen commented on Sep 3, 2026

    @kynbeen

    Still reproducing, and on a code path the reports here haven't covered: Windows, where the store is the plaintext ~/.claude/.credentials.json rather than the macOS Keychain (tengu_windows_credman resolves to false, so VG() returns the plaintext store and every process shares one file). Filed with logs and the relevant code in #91708.

    Short version of the mechanism, from the shipped v2.1.258 bundle:

    var FD4 = 300000;                                  // 5 min
    function mB$($) { return Date.now() + FD4 >= $; }  // "expiring soon?"

    Every process picks the same 5-minute pre-expiry window, and the de-dup guard is in-process only:

    if (this.pendingRefresh) return this.pendingRefresh;   // no cross-process lock

    So N concurrent processes make N refresh calls at once; the losers replay a consumed refresh token and get a 400, which under RFC 9700 reuse detection takes the whole token family down — the 27-day refresh token, not just one request.

    One note for anyone landing here from search: CLAUDE_CODE_OAUTH_401_WAIT_MS (suggested above) does not apply to file-store setups. The wait path is gated on an env-var token:

    let T = Boolean(process.env.CLAUDE_CODE_OAUTH_TOKEN) || Boolean(wH());
    if (T) { let y = npe(); if (y > 0) { /* wait for a rotated env token */ } }

    With plain .credentials.json auth, T is false and the wait never runs.

  20. MaddyMurder commented on Sep 29, 2026

    @MaddyMurder

    Can this be re-opened? Closed with no explanation makes no sense as this is still unfixed, and clearly a bug

  21. vdavid commented on Sep 29, 2026

    @vdavid

    You're probably right that this issue is unresolved and shouldn't be closed.
    </consolation>
    My limited but practical tips for you to solve this:
    What I did was to send Claude a link to this issue, and asked it to dig. This was like a month ago, and it did something that solved it for me, never had my sessions interrupted with the auth since. I did get the full picture back then, and the solution wasn't too crazy, I just completely forgot about what it was. I now tried to dig up that session but can't find it :( So my best tip is to ask Claude to get it fixed for you and it probably will.

  22. github-actions commented on Nov 25, 2026

    @github-actions

    This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.

  23. locked as resolved and limited conversation to collaborators on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:authbughas reproplatform:macos

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions