Fix Gemini CLI "401 UNAUTHENTICATED" Mid-Session Error and Login Auth Loops
Fix the Gemini CLI "401 UNAUTHENTICATED" mid-session error and infinite browser login loops by clearing ~/.gemini/oauth_creds.json, unsetting conflicting Google Cloud variables.
Summary
- Mid-session 401 UNAUTHENTICATED errors (often with ACCESS_TOKEN_TYPE_UNSUPPORTED) happen when a 60-minute OAuth token fails to refresh silently or collides.
- Infinite browser login loops occur when another process (such as a VS Code extension) overwrites ~/.gemini/oauth_creds.json or when a firewall or container.
- Delete ~/.gemini/oauth_creds.json, unset GOOGLE_CLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS.
When Gemini CLI drops a 401 UNAUTHENTICATED error halfway through a coding session—or traps you in an endless browser login loop where every successful sign-in immediately opens another login tab—your Google account password is not the problem. The failure happens locally between your ~/.gemini credential cache, your shell environment variables, and the endpoint Gemini CLI is trying to call.
In a mid-session drop, the terminal usually prints this exact payload:
✕ [API Error: {"error":{"message":"{\n \"error\": {\n \"code\": 401,\n \"message\": \"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n \"status\": \"UNAUTHENTICATED\",\n \"details\": [\n {\n \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n \"reason\": \"ACCESS_TOKEN_TYPE_UNSUPPORTED\",\n \"metadata\": {\n \"service\": \"generativelanguage.googleapis.com\",\n \"method\": \"google.ai.generativelanguage.v1beta.GenerativeService.StreamGenerateContent\"\n }\n }\n ]\n }\n}\n","code":401,"status":""}}]
In a login loop, the CLI opens your browser, you approve access, the terminal prints ℹ Authentication succeeded, and half a second later it prints ℹ Attempting to open authentication page in your browser. Otherwise navigate to: https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http%3A%2F%2F127.0.0.1%3A<PORT>%2Foauth2callback... over and over.
| Symptom in Terminal | Root Cause | Immediate Fix |
|---|---|---|
401 UNAUTHENTICATED with ACCESS_TOKEN_TYPE_UNSUPPORTED |
GOOGLE_CLOUD_PROJECT or GOOGLE_APPLICATION_CREDENTIALS is set in your shell, sending Cloud ADC tokens to the consumer generativelanguage.googleapis.com endpoint. |
Unset all GOOGLE_CLOUD_* and GOOGLE_APPLICATION_CREDENTIALS variables, then restart gemini. |
401 UNAUTHENTICATED after ~60 minutes of active chatting |
The short-lived OAuth access token expired and the background refresh failed due to network sleep, proxy TLS inspection, or file lock. | Delete ~/.gemini/oauth_creds.json to force a clean token pair, or switch to GEMINI_API_KEY. |
Authentication succeeded followed immediately by another browser login prompt |
~/.gemini/oauth_creds.json is being wiped or locked by a conflicting IDE plugin, or GOOGLE_CLOUD_PROJECT is forcing an enterprise subscription check on a personal account. |
Unset GOOGLE_CLOUD_PROJECT, close conflicting Gemini IDE extensions, and remove ~/.gemini/oauth_creds.json. |
Browser hangs or fails on 127.0.0.1:<PORT>/oauth2callback |
Running inside WSL, Docker, or remote SSH where the random local loopback port cannot receive the browser redirect. | Bypass browser OAuth entirely by exporting GEMINI_API_KEY. |
On this page
Why Gemini CLI Throws "401 UNAUTHENTICATED" Mid-Session
According to the Google Cloud Agent Platform API errors reference and the Google AI Studio error documentation, an HTTP 401 (UNAUTHENTICATED or authentication) means the gateway rejected your request before model inference started because the credential header was missing, expired, or incompatible with the target service.
When I debug mid-session 401s in Gemini CLI, they always come down to one of two local state collisions.
The first is a silent OAuth refresh failure. When you choose Sign in with Google using a personal Google account (including Google AI Pro or Ultra subscriptions), Gemini CLI writes an OAuth access token and a refresh token to ~/.gemini/oauth_creds.json. Google OAuth access tokens expire after 60 minutes. Normally, the CLI uses the refresh token to fetch a new access token silently in the background. If your laptop sleeps during a long session, your VPN switches routes, or a corporate firewall intercepts the refresh handshake, the background renewal fails. On your very next prompt, the CLI sends the expired token and hits a 401.
The second—and more confusing—cause is a credential-to-endpoint mismatch, which triggers "reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED". By default, Gemini CLI sends streaming requests to generativelanguage.googleapis.com (GenerativeService.StreamGenerateContent). However, if you work with Google Cloud or Vertex AI in the same terminal environment and have GOOGLE_APPLICATION_CREDENTIALS or GOOGLE_CLOUD_PROJECT exported in your shell profile, the underlying Google auth library picks up your Application Default Credentials (ADC) or service account token. When Gemini CLI attaches that Cloud token to a request aimed at the consumer AI Studio endpoint—or tries to validate a personal OAuth token against an enterprise project—the gateway rejects the token type immediately.
Fix 1: Unset Conflicting Google Cloud Variables and Reset ~/.gemini
If you are signing in with an individual Google account, your environment must be completely free of Google Cloud project variables. As documented in the official Gemini CLI Troubleshooting Guide, if Gemini CLI detects GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID, it forces an enterprise organization check for a Gemini Code Assist Standard edition subscription. On a personal account, that check either fails authentication outright or causes mid-session credential conflicts.
First, strip the conflicting variables from your current shell session:
# macOS / Linux
unset GOOGLE_CLOUD_PROJECT
unset GOOGLE_CLOUD_PROJECT_ID
unset GOOGLE_APPLICATION_CREDENTIALS
# Windows (PowerShell)
Remove-Item Env:\GOOGLE_CLOUD_PROJECT -ErrorAction Ignore
Remove-Item Env:\GOOGLE_CLOUD_PROJECT_ID -ErrorAction Ignore
Remove-Item Env:\GOOGLE_APPLICATION_CREDENTIALS -ErrorAction Ignore
Make sure you also check your ~/.zshrc, ~/.bashrc, or any .env file in your current working directory. If those variables are hardcoded in your startup scripts or project .env, they will silently reload the next time you open a terminal tab.
Next, delete the cached OAuth credential file so the CLI does not try to reuse a corrupted or mismatched token pair. You do not need to wipe your entire ~/.gemini directory; leaving settings.json alone preserves your theme and tool preferences:
# macOS / Linux
rm -f ~/.gemini/oauth_creds.json
# Windows (PowerShell)
Remove-Item -Path "$HOME\.gemini\oauth_creds.json" -Force -ErrorAction SilentlyContinue
If your session state is still wedged, remove ~/.gemini/trustedFolders.json alongside oauth_creds.json and update the CLI binary so you are not running an older release with known token-refresh bugs:
npm install -g @google/gemini-cli@latest
Fix 2: Break the Infinite Browser Login Loop (oauth2callback)
Nothing is more frustrating than watching the browser say you are signed in, seeing ℹ Authentication succeeded in the terminal, and immediately getting bounced back to https://accounts.google.com/o/oauth2/v2/auth on a new 127.0.0.1 port.
When Authentication succeeded prints in the terminal, the local OAuth callback listener actually received the authorization code from your browser. The loop happens because the token disappears or fails validation between the callback step and the start of the interactive prompt.
In my experience, the primary culprit is file contention on ~/.gemini/oauth_creds.json. If you have VS Code or another IDE open with the Gemini Code Assist extension active—or if you have a stale gemini process hanging in another terminal window—both processes monitor and write to the same credential store. Right after the CLI writes your fresh token to ~/.gemini/oauth_creds.json, the competing process either overwrites the file or revokes the previous token family. When the CLI initializes the chat session a moment later, it reads an invalid state and triggers the browser login all over again.
To stop the loop:
- Close any active Gemini Code Assist IDE extensions or secondary terminal tabs running
gemini. - Check for orphaned Node processes (
ps aux | grep geminion macOS/Linux) and terminate them. - Delete
~/.gemini/oauth_creds.jsonand rununset GOOGLE_CLOUD_PROJECTas shown above, then launchgeminiin a single clean terminal.
If the loop happens before Authentication succeeded ever prints in the terminal, the browser redirect to http://127.0.0.1:<PORT>/oauth2callback is not reaching the CLI process. Gemini CLI binds to a random ephemeral port on localhost. If you run the CLI inside a Docker container, over a remote SSH session without port forwarding, or inside a WSL2 instance where a local firewall drops loopback traffic on high ports, the callback packet never lands. Instead of fighting port forwarding rules every time the random port changes, switch to an API key.
Fix 3: Switch from OAuth to GEMINI_API_KEY (The Permanent Bypass)
Whenever I run Gemini CLI in headless environments, remote servers, or machines where Google Cloud SDK variables (gcloud) have to stay active for my day job, I do not use browser OAuth at all. Switching to a static Gemini API Key bypasses ~/.gemini/oauth_creds.json, eliminates 60-minute token refresh drops, and ignores the 127.0.0.1 loopback listener completely.
Generate a key from the Google AI Studio API Key page and export it in your shell:
# macOS / Linux
export GEMINI_API_KEY="AIzaSyYourActualKeyHere"
# Persist it in your shell profile
echo 'export GEMINI_API_KEY="AIzaSyYourActualKeyHere"' >> ~/.zshrc
source ~/.zshrc
# Windows (PowerShell)
$env:GEMINI_API_KEY="AIzaSyYourActualKeyHere"
[Environment]::SetEnvironmentVariable("GEMINI_API_KEY", "AIzaSyYourActualKeyHere", "User")
Before launching gemini, verify that you do not have GOOGLE_API_KEY or GOOGLE_APPLICATION_CREDENTIALS set from a separate Vertex AI setup. Mixing Vertex ADC variables with GEMINI_API_KEY causes the client router to send your AI Studio key to the wrong authentication handler. Once your environment is clean, run gemini and select Use Gemini API key from the authentication prompt.
If you switch to an API key and your 401 disappears, but you immediately run into 404 Not Found on v1beta models or 429 RESOURCE_EXHAUSTED quota blocks, check my breakdown on fixing Gemini 3 Flash 404, 400, and 429 API errors to align your model IDs and billing tier.
Fix 4: Corporate Firewalls, Custom Gateways, and Multi-CLI Config
If you are on a corporate network or routing Gemini CLI through a custom API relay, 401 and TLS errors often happen outside Google's official endpoints.
Corporate firewalls that perform SSL/TLS deep packet inspection replace Google's certificate chain with an internal root CA. Because Gemini CLI runs on Node.js, which uses its own bundled CA store rather than your operating system's keychain by default, the background OAuth token refresh or API handshake gets blocked. Tell Node.js to trust your system's native certificate store before starting the CLI:
export NODE_USE_SYSTEM_CA=1
If you route Gemini CLI through a self-hosted proxy or an enterprise LLM gateway using GOOGLE_GEMINI_BASE_URL, a 401 UNAUTHENTICATED error usually means the gateway expects a custom bearer key while your CLI is still trying to attach a Google OAuth token from ~/.gemini/oauth_creds.json. Clear oauth_creds.json and pass the gateway's key via GEMINI_API_KEY:
export GOOGLE_GEMINI_BASE_URL="https://your-gateway.example.com"
export GEMINI_API_KEY="your-gateway-key"
When you juggle multiple terminal coding agents at once—such as Gemini CLI, Claude Code, and OpenAI Codex CLI—keeping track of which shell tab has which Base URL, API key, and cached OAuth token exported quickly turns into a mess. It is the exact same environment collision pattern that causes Codex CLI to throw "401 Unauthorized: Incorrect API key provided" while signed in.
To stop debugging shell profiles by hand, our team at SeedRouter built the open-source LLM API Config GUI (GitHub repo) for macOS and Windows. It gives you a clean desktop interface to manage Base URLs, API keys, and model mappings for Codex and Claude Code, export configurations directly to CC Switch, and run one-click connection tests that diagnose 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Rate Limit, and timeout errors before you start a terminal session.