Skip to content

[BUG] OAuth token expiration disrupts autonomous workflows – refresh token handling needed #12447

Open

Description

@brupelo

Preflight Checklist

  • I have searched existing issues and this hasn't been reported yet
  • This is a single bug report (please file separate reports for different bugs)
  • I am using the latest version of Claude Code

What's Wrong?

OAuth token expiration disrupts autonomous workflows – refresh token handling needed

Environment:

  • Claude Code version: 2.0.45
  • Platform: Docker (headless/autonomous operation)

Problem

OAuth tokens expire during long-running autonomous tasks, causing 401 authentication_error failures that require manual /login intervention. When running multiple concurrent Claude Code instances dispatching work over extended periods (hours/days), token expiration halts all in-progress tasks simultaneously, leaving work in incomplete states.

API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."},"request_id":"..."}

Combined with occasional 500 errors (separate issue, but compounding), sustained autonomous operation is currently not viable.

Why This Feels Like a Bug (Not Just a Security Feature)

I understand short-lived tokens are a security best practice—limiting exposure if credentials leak. However:

  1. OAuth has a standard solution for this: refresh tokens. Short-lived access tokens + automatic refresh gives you both security AND seamless operation. The current implementation seems to require manual re-authentication rather than handling refresh transparently.

  2. The failure mode is destructive. Tasks don't gracefully pause and resume—they leave branches and work in half-finished states. If the intent is to require periodic human check-ins, a cleaner approach would be to pause work cleanly and queue for resumption, not crash mid-task.

  3. No visibility into expiration timing. I can't plan around this because I don't know when expiration will occur. If human oversight is the goal, at least let me see "token expires in X hours" so I can schedule accordingly.

  4. If limiting autonomous operation is intentional, there are better mechanisms: explicit autonomous-mode opt-in, spending caps, task duration limits, or configurable session lengths. The current behavior doesn't prevent autonomous use—it just makes it frustrating and wastes work.

What I'm Trying to Do

Run multiple Claude Code instances in Docker containers, dispatching and processing issues continuously over several days. This requires:

  • Reliable authentication that doesn't require babysitting
  • Graceful handling of transient failures (auth, network, API errors)
  • Ability to resume interrupted work

Question for Maintainers

Is the current behavior intentional to discourage long-running autonomous agents, or is this simply an implementation gap in the OAuth flow? If it's intentional, I'd appreciate understanding the reasoning—and would suggest that explicit guardrails (spending limits, duration caps, opt-in autonomous mode) would be a better UX than silent auth failures.


This is currently a significant blocker for autonomous agentic workflows. Happy to provide more details or test any proposed fixes.

What Should Happen?

Proposed Solutions (Pick Any)

  1. Implement proper refresh token handling – Transparently refresh access tokens before expiration. This is the standard OAuth pattern.

  2. Expose token lifetime configuration – Let users set token expiration duration (like Azure DevOps, GitHub PATs, etc.). Those running supervised can use short tokens; those running autonomous can accept the security trade-off.

  3. Add session resumption – If auth fails mid-task, persist state so work can resume after re-authentication rather than leaving repos in broken states.

  4. Show expiration time – At minimum, display when the current token expires (/status or similar) so users can plan around it.

Error Messages/Logs

API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing
     token."},"request_id":"req_011CVWAKo6VpooYthEXLYEYe"} · Please run /login

Steps to Reproduce

Environment setup:

  1. Run Claude Code in a Docker container (headless, no interactive terminal)
  2. Authenticate via /login
  3. Dispatch one or more long-running tasks (e.g., complex refactoring, multi-file changes, issue-driven workflows)

Reproduction:

  1. Start a task that takes 30+ minutes, or start multiple concurrent tasks
  2. Leave running unattended for several hours (I've seen this trigger within 2-4 hours, but exact timing is unpredictable)
  3. Return to find all instances stopped with 401 authentication_error

Observed behavior:

  • All running tasks fail simultaneously with OAuth expiration error
  • Work is left in incomplete state (partial commits, uncommitted changes, mid-process branches)
  • Requires manual /login to resume
  • No warning before expiration occurs

Expected behavior:

  • Token refreshes automatically before expiration
  • Or: tasks pause gracefully and resume after re-authentication
  • Or: at minimum, token expiration time is visible so users can plan around it

Frequency: Happens consistently when running tasks over extended periods. Not a rare edge case.

Note: Exact expiration timing is unknown—this is part of the problem. If there's a way to inspect token TTL, please share and I can provide more precise reproduction timing.

Claude Model

None

Is this a regression?

Yes, this worked in a previous version

Last Working Version

No response

Claude Code Version

2.0.45 (Claude Code)

Platform

Anthropic API

Operating System

Windows

Terminal/Shell

Windows Terminal

Additional Information

No response

Activity

  1. added
    bug
    on Nov 26, 2025
  2. added
    has repro
    platform:windows
    on Nov 26, 2025
  3. onikiienko commented on Dec 2, 2025

    @onikiienko

    We also observe this problem in Xcode. Have to sign out and log in once a day.

  4. maxjendrall commented on Dec 8, 2025

    @maxjendrall

    If I am not entirely wrong, I was able to solve it by doing "claude setup-token" instead of /login within the interactive shell.

    It says: "Your OAuth token (valid for 1 year)" and "✓ Long-lived authentication token created successfully!"

  5. lsscodes commented on Dec 13, 2025

    @lsscodes

    @toorusr I tried your suggestion and was able to create a long-lived aut token, but i am still getting this error in claude(code) destop app

    Image
  6. brupelo commented on Dec 15, 2025

    @brupelo
    Author

    Hi guys, thanks for the feedback and suggestions! That sounds really good—exactly what was needed. /login won’t cut it. I haven’t had time to try it yet, but I’ll give it a shot once my usage is back… crazy how fast the Max plan gets used up—four days of idling already because all models maxed out in a blink of an eye. IMHO It’s quite expensive for the limited usage you get from the Claude API and the extra usage is very expensive, times when i used maxed out in few minutes, but that’s off-topic.

    With this approach, I assume you’d be able to use a single authorization token that you can easily revoke from https://claude.ai/settings/claude-code and share across different agents, right?

    Right now, I’m running multiple Docker environments, and in each one I have to log in manually once and then share credentials across all containers. It would be great if I could instead share a single token across all environments.

    As long as this provides proper control over expiration and revocation, it sounds like the right solution.

  7. mitchcapper commented on Dec 16, 2025

    @mitchcapper

    manual long lived token is really not the solution plenty of apps used refresh tokens and can properly refresh the session. Case and point simply restarted claude code and it is good to go, there is no reason it shouldn't be able to keep its session alive. @lsscodes the desktop app doesn't have a similar option thus the continued issue.

  8. ftballguy45 commented on Dec 17, 2025

    @ftballguy45

    now getting asked daily to relogin to claude desktop 👎

  9. ElCativoGER commented on Dec 21, 2025

    @ElCativoGER

    I am using claude Desktop and can´t login to Code. Everything ist fin but Code is not working. Always getting Token failure...
    /login does nothing
    Manually logoff login does nothing, still error.
    Can´t work anymore, please help.
    Running on Windows with Google Auth.

  10. PowerAppsDarren commented on Dec 26, 2025

    @PowerAppsDarren

    I'm on the 20x Max Plan.

    This has become worse for recently. I'm burning through all my credits for spawned sub agents, then those agents are coming back with oauth error telling me to log in. I'm sorry, it is not feasible to sit at my computer and monitor for these 401 errors 20 or more times a day. We shouldn't have to.

    API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."},"request_id":"req_011CWR6QbR9zivmQtHS6Tzck"} · Please run /login
    
    
    
      Time: 2025-12-25 19:26 | Claude Agents: 72 active
    
      Repository Progress
    
      +-------------------+--------+------+------------------------------------+
      | Repository        | Status | Iter | Progress                           |
      +-------------------+--------+------+------------------------------------+
      | PROJECT-NAME      | [OK]   |  331 | ████████████████████████████████ * |
      | PROJECT-NAME      | [OK]   |  331 | ████████████████████████████████ * |
      | PROJECT-NAME      | [OK]   |  313 | ██████████████████████████████   * |
      | PROJECT-NAME      | [OK]   |   69 | ███████                            |
      | PROJECT-NAME      | [OK]   |   69 | ███████                            |
      | PROJECT-NAME      | [OK]   |   69 | ███████                            |
      | PROJECT-NAME      | [>>]   |   68 | ██████▓                            |
      | PROJECT-NAME      | [OK]   |   68 | ███████                            |
      | PROJECT-NAME      | [OK]   |   67 | ███████                            |
      | PROJECT-NAME      | [OK]   |   67 | ███████                            |
      | PROJECT-NAME      | [OK]   |   66 | ██████                             |
      | PROJECT-NAME      | [>>]   |   65 | ██████▓                            |
      | PROJECT-NAME      | [OK]   |   59 | ██████                             |
      | PROJECT-NAME      | [OK]   |   59 | ██████                             |
      +-------------------+--------+------+------------------------------------+
      [OK] = completed | [>>] = running | * = high activity
    
      Warning: Zero Progress Alert
    
      +--------------------------------------------------------------+
      | [!] ZERO_PROGRESS: 744 consecutive sessions with 0 files     |
      |     modified. Agents are running but not producing output.   |
      +--------------------------------------------------------------+
    
      The cost monitoring is flagging:
      - 744 consecutive sessions with no file changes
      - Burn rate warnings (cost calculation seems off - likely a bug in the metrics)
    
    ----
    
    Claude CLI auth is expired and sessions are still marked completed: repeated API Error: 401 ... Please run /login in iteration reports like 2025-12-25-061-review-the.md and 2025-12-25-023-add-tests.md; agent.py treats any response text as “completed,” so these failures keep re-queuing with zero edits.
    Zero-progress count only resets on nonzero files_modified (orchestrator_monitor.py), so auth-failed or read-only runs quickly compound to 744.
    File-change tracking only counts Edit/Write tool calls with file_path (agent.py), while many sessions only show Bash/Read/TodoWrite/mcp__... tools (e.g., 2025-12-25-060-add-tests.md), so real changes via shell/MCP are missed.
    MCP output shows allowed dir /C/src while repos are A:\src (see 2025-12-25-060-review-review.md), which can block file writes even when auth works.
    mission.max_cycles_per_repo isn’t enforced; cycle-mode re-queues unconditionally in orchestrator.py, amplifying repeated zero-output sessions.
    Burn-rate warnings use estimated tokens/hour but label them as dollars (orchestrator_monitor.py, cost_tracker.py), which matches the “cost calc seems off” complaint.
    Recommended Next Steps
    
    Re-authenticate Claude CLI (claude /login or ensure ANTHROPIC_API_KEY is valid) and verify a single run produces tool calls and no 401s.
    Treat auth failures as error in agent.py (e.g., detect authentication_error in response text) so the orchestrator doesn’t re-queue failed sessions.
    Track file changes via git status --porcelain per repo (or expand tool-name/path matching) so zero-progress reflects real output.
    Enforce mission.max_cycles_per_repo and/or stop after N consecutive zero-change sessions to prevent infinite cycling.
    Fix burn-rate units (tokens/hour vs USD) and use CostTracker.cost_usd if you want dollar-based alerts.
    
    
    
    Image Image
  11. BlindGuyNW commented on Jan 4, 2026

    @BlindGuyNW

    Just chiming in here as a desktop user who's noticed this (exclusively on desktop) recently. It makes using the app very frustrating as I can't seem to return to a session after it happens.

  12. zonnenberg commented on Jan 7, 2026

    @zonnenberg
    Image

    Same here in Claude Code Desktop. Yesterday I started a few sessions, and now all those existing sessions don't work anymore. After starting a new session and logging in, only that session works.

    Steps to reproduce:

    1. Open Claude Code Desktop
    2. Authenticate with Google OAuth
    3. Start one or more sessions and use them normally
    4. Wait approximately 24 hours (or until OAuth token expires)
    5. Open Claude Code Desktop again
    6. Try to continue working in one of the existing sessions from step 3 (even /login does nothing)
    7. Observe the error
    8. Start a new session – observe that it works correctly
    9. Existing sessions still not working, giving the same error message again

    Update: Temp workaround is to go to the folder and start Claude CLI with claude -r, then continue the session from there.

  13. 4 remaining items

  14. mieubrisse commented on Feb 10, 2026

    @mieubrisse

    I'm getting the dreaded

    API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}

    multiple times per day now. this is pretty crazy.

  15. WynnD commented on Feb 21, 2026

    @WynnD

    I have this same issue on Ubuntu 25.10 using Claude Code version 2.1.50

  16. 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

  17. mieubrisse commented on Feb 21, 2026

    @mieubrisse

    Same issue being tracked on #24317 , and there has more forensics on exactly why this happens

  18. prong-raft-squishy commented on Feb 23, 2026

    @prong-raft-squishy

    Adding data from an autonomous workflow use case. I run Claude Code headless via launchd (macOS cron equivalent) for scheduled maintenance tasks — security audits, fleet health checks, content processing. These are non-interactive sessions launched with claude -p through a wrapper script.

    The pattern: a 60-second auth pre-flight check passes, then the actual session runs for 1-3 hours and dies mid-execution with OAuth token has expired. This affects multiple scheduled jobs per week — out of 15 scheduled skills, auth expiry is the #1 failure mode (3 of 5 recent failures).

    The pre-flight check is essentially worthless for long sessions because it only proves the token is valid right now, not that it will survive the session duration. A token refresh mechanism or longer TTL would make autonomous Claude Code workflows significantly more reliable. Currently there's no recovery path — the session just dies and the work is lost.

  19. mieubrisse commented on Feb 24, 2026

    @mieubrisse
  20. lonetis commented on Feb 28, 2026

    @lonetis

    Do you use the same refresh token across multiple isolated Claude Code instances? Claude uses refresh token rotation (https://datatracker.ietf.org/doc/html/rfc9700#section-2.2.2). When a client redeems a refresh token, the server invalidates it and issues a new one. As a result, two machines can’t share the same refresh token. One machine redeems it and stores the rotated token, while the other keeps using the old token and fails.

  21. mieubrisse commented on Mar 5, 2026

    @mieubrisse

    The result of claude setup-token is valid for a year; I haven't had a problem with it since setting it up

  22. oorestisime commented on Mar 11, 2026

    @oorestisime

    The result of claude setup-token is valid for a year; I haven't had a problem with it since setting it up

    Is this an api token or a subscription token ?

  23. mieubrisse commented on Mar 11, 2026

    @mieubrisse
  24. 42piratas commented on Mar 30, 2026

    @42piratas

    Any updates on this?

  25. jlacroix82 commented on Aug 28, 2026

    @jlacroix82

    I am seeing the same forced re-authentication, and in my case it is not limited to Linux or to a reboot.

    I am repeatedly asked to authenticate across every surface I use: iOS, Claude on the web under Windows, the Windows desktop app, and the Linux desktop app. It happens sometimes multiple times a day. Signing in on one surface does not appear to spare me on the others.

    That breadth may mean this issue is narrower than the underlying problem — the title scopes it to dual accounts, Linux and reboot, but I hit re-authentication on single-surface use with no reboot involved, on platforms other than Linux.

    One concrete instance from today, on the Linux desktop app (1.37937.3, Electron 42.10.0): a session that had been idle roughly 8 hours came back with HTTP 403 session_stale_relogin on file access to the connected device. Notably the connection was only partly invalidated — directory listing and writes to the device still succeeded, only reads were refused. I have written that up in more detail on #12447 in case the asymmetry helps narrow it down.

    The re-authentication itself is quick. The problem is that it is frequent, unpredictable, lands mid-task, and repeats per surface — which makes anything long-running or unattended unreliable to plan around.

  26. Ryzodus-RB42 commented on Sep 8, 2026

    @Ryzodus-RB42

    Chiming in with a workaround that's held for us — not a fix, and I'd welcome anyone confirming it generalizes.

    Setup: 7 headless agents on a Linux box (systemd, nightly runs), same Max account also logged into the desktop app. Hit this exactly — all agents dying overnight with OAuth session expired and could not be refreshed, and the credentials file left zeroed. @lonetis's read above matches what we found: the desktop sessions and the headless runner shared one rotating refresh token, and whichever refreshed last invalidated the other's copy.

    Two things worth flagging:

    1. setup-token "works" but silently strips claude.ai connectors. A CLAUDE_CODE_OAUTH_TOKEN credential can only make model requests — Gmail/ClickUp/etc. connectors just aren't present. Our agents ran, exited 0, and did nothing, which was worse than failing loudly. (Noted in #76905, but easy to miss from this thread.) So if your headless workload needs connectors, setup-token isn't the answer.

    2. What's held for us: give the headless runner its own login in a separate config dir instead of sharing the default one:

    CLAUDE_CONFIG_DIR=~/.claude-fleet claude login
    

    Then export CLAUDE_CONFIG_DIR=~/.claude-fleet before the headless invocations. Same account, so claude.ai connectors are inherited automatically (verified — they show Connected and work in -p runs). But it's its own credentials.json / own refresh-token family, so the desktop app's rotation can't invalidate it. The access token still rotates ~8h; the point is isolation, not a long-lived token.

    Honest caveats: the initial login is interactive — you need a browser once, it can't be fully scripted. Locally-added MCP servers (claude mcp add) don't cross over and must be re-added in the new config dir; account-level claude.ai connectors do. And I've only proven it over a week of nightly runs — it survives the desktop rotating its token, but I can't speak to months yet.

    Would be glad if others can confirm it holds on their setups.

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:windows

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions