LLM API Guide

Fix Codex "unexpected status 401 Unauthorized: Incorrect API key provided"

Fix "unexpected status 401 Unauthorized: Incorrect API key provided" in Codex CLI, Desktop, and VS Code when signed in with a ChatGPT subscription or API key.

Summary

  1. Check the error's URL and masked key prefix first.
  2. If the URL is api.openai.com/v1/responses and the key reads dummy, a local ChatGPT OAuth refresh failed mid-session; fix it with codex logout and codex login.
  3. On the Windows Codex Desktop app, enabling Advanced Account Security can invalidate refresh tokens whenever you open a thread.
  4. Check for stray OPENAI_API_KEY or CODEX_API_KEY environment variables and conflicting requires_openai_auth / env_key rules in ~/.codex/config.toml.

When you sign in to the Codex CLI, Desktop app, or VS Code extension with a ChatGPT Plus, Pro, Team, or Enterprise subscription, you never generate or paste an OpenAI Platform API key. Getting hit mid-session with unexpected status 401 Unauthorized: Incorrect API key provided—often printing a masked key you have never seen before—looks like your account was hijacked or corrupted. To make it more confusing, running codex login status right after the crash still prints Logged in using ChatGPT.

You see an API key error on a subscription login because Codex routes requests through two different authentication layers, and codex login status only checks whether a credential file exists locally in ~/.codex/auth.json or your OS keychain without testing it over the network. Before you delete local state files or touch your configuration, read the url: field and the masked key prefix in the error line. Those two strings tell you immediately whether OpenAI's backend is down, your local OAuth token failed to refresh, or an environment variable is hijacking your session.

On this page

Match Your Exact 401 Error to the Cause

Here is how a typical subscription-mode failure looks when the error is thrown from the ChatGPT backend route:

text
unexpected status 401 Unauthorized: Incorrect API key provided: sk-svcac************************************************************************************************************************************************fvMA.
You can find your API key at https://platform.openai.com/account/api-keys.,
url: https://chatgpt.com/backend-api/codex/responses, cf-ray: a40d95aa6bfcb8db-SEA, request id: 436e8c67-7c9a-4980-995e-ba89a1bd5957

Compare the url and key string in your terminal against this diagnostic table to pinpoint which failure you are dealing with:

Error URL and Key Text What codex login status Shows Root Cause Immediate Fix
url: https://chatgpt.com/backend-api/codex/responses with key sk-svcac... Logged in using ChatGPT OpenAI's edge gateway rejected its own internal service-account key while forwarding your subscription request. Check status.openai.com. Leave local files alone, or temporarily switch to a platform API key.
url: https://api.openai.com/v1/responses (or wss://...) with key dummy Logged in using ChatGPT Local OAuth token refresh failed after a network change or sleep, and Codex fell back to a hardcoded dummy placeholder key. Run codex logout followed by codex login.
url: https://api.openai.com/v1/responses with key sk-proj-... or sk-... Logged in using ChatGPT or API key A stray OPENAI_API_KEY or CODEX_API_KEY environment variable, or a cached key in auth.json, is overriding your session. Unset the environment variable or pipe a valid key into codex login --with-api-key.
refresh_token_invalidated or Your access token could not be refreshed Logged in using ChatGPT Reused single-use refresh token across synced machines, stale web session, or the Windows Advanced Account Security refresh bug. Log out of all sessions at chatgpt.com, then run codex logout && codex login.
Custom gateway URL with Invalid or expired API key or You didn't provide an API key Either mode requires_openai_auth = true is overriding env_key in config.toml, or your exported key contains a trailing newline or literal quotes. Remove requires_openai_auth when using env_key, and strip \n, \r, and " from the variable.

Why sk-svcac Appears When You Never Set an API Key

When you use Codex with a ChatGPT subscription, your client does not talk to api.openai.com. Instead, it sends your OAuth bearer token to https://chatgpt.com/backend-api/codex/responses (or its wss:// WebSocket counterpart). Once OpenAI's edge gateway validates your ChatGPT session, it forwards your prompt to internal model microservices using OpenAI's own internal service-account credentials—which use the sk-svcac prefix. If that internal credential is revoked or rejected upstream, the microservice returns a standard OpenAI Platform 401 error, and the gateway passes that raw message straight back to your terminal.

This chain reaction caused the global Codex outage on September 25, 2026. As documented in OpenAI's official incident write-up, between 15:33 and 16:47 PDT (22:33–23:47 UTC), OpenAI's internal credential leak detection system triggered a false positive on the internal service credentials supporting Codex. A manual operation overrode internal checks and revoked them. For 74 minutes—starting 25 minutes before the status page even opened an incident ticket—ChatGPT-signed-in users across macOS, Windows, and Linux received the same sk-svcac***...***fvMA error, while customers authenticating directly with their own platform API keys did not encounter this credential error.

When your error points to chatgpt.com/backend-api/codex/responses and displays an sk-svcac key, nothing on your computer is broken. Do not delete ~/.codex/state_5.sqlite (which permanently wipes your local task and thread history) and do not waste time downgrading your CLI binary. Separating an upstream OpenAI fault from a local account problem saves you from breaking a working setup—the same diagnostic check I use when troubleshooting Codex "Selected Model Is at Capacity": OpenAI Load or Your Account? or verifying whether your Codex account was silently downgraded.

Fixing Stale ChatGPT Sessions and the dummy Key Fallback

If status.openai.com shows all Codex components operational and you are still getting a 401 while signed in with ChatGPT, your local OAuth state is out of sync with OpenAI's authentication server.

One frequent culprit in Codex CLI (0.145.0 and later) is the dummy key fallback. When your laptop wakes from sleep, switches Wi-Fi networks, or drops a VPN tunnel right as Codex tries to refresh its OAuth access token, the refresh call fails. Instead of halting immediately with an OAuth error, the client can fall back to calling wss://api.openai.com/v1/responses with a hardcoded dummy bearer string, which the API server rejects with Incorrect API key provided: dummy.

A related failure happens if you sync ~/.codex/auth.json across two machines via dotfiles or bake it into a Docker container. Codex sets TOKEN_REFRESH_INTERVAL to 8 days, and OpenAI's OAuth refresh tokens are strictly single-use. The first machine to refresh after the window consumes the token and receives a new pair; the second machine tries to use the old refresh token and fails with Your access token could not be refreshed because your refresh token was already used or revoked.

To clear a broken local token, reset the credential store from your terminal:

bash
codex logout
codex login

If you are working on a remote SSH server or headless container where a local browser cannot open, run the device-code flow instead:

bash
codex logout
codex login --device-auth

Because the Codex CLI and the VS Code extension share ~/.codex/auth.json, logging out and back in from the terminal fixes both tools at once. Also make sure your CLI is updated to at least 0.159.0 or 0.160.0, as 0.156.0 fixed OAuth login recovery behind system proxies and 0.159.0 fixed browser launch failures during local ChatGPT sign-in.

When codex logout Still Loops: Flush All Web Sessions

When you return to Codex after several weeks away, or when multiple devices hold half-expired OAuth grants, running codex logout && codex login locally can still drop you right back into unexpected status 401 Unauthorized: Incorrect API key provided. Your browser simply re-attaches the new CLI token to a stale session on OpenAI's web auth server.

To break that loop permanently, open chatgpt.com in your browser, go to Settings -> Security, and click Log out of all sessions. Wait about thirty seconds for OpenAI's backend to invalidate all active device grants, sign back in to the web app, and then run codex login in your terminal.

The Windows Desktop App + Advanced Account Security Bug

If you use the Codex Desktop app on Windows (such as stable build 26.818.21641) and have Advanced Account Security enabled on your OpenAI account, you can hit an immediate 401 loop even after a clean sign-in. Initial OAuth login succeeds and writes valid tokens to ~/.codex/auth.json, but the moment you open a new thread or resume an existing session, the stable Windows client calls getAuthStatus and fires an aggressive POST https://auth.openai.com/oauth/token refresh request. That premature refresh collides with the stricter security policy on the server and returns:

text
401 Unauthorized
code: refresh_token_invalidated
message: "Your refresh token has been invalidated. Please try signing in again."

Because the bug is triggered by the stable Windows desktop wrapper's thread-resume timing rather than your account credentials, re-logging in only works until you click into another thread. Until the stable desktop release matches the token refresh behavior of the beta branch, run your sessions through the Codex CLI or install the Codex Beta desktop build on Windows.

Environment Variables and config.toml Sending the Wrong Key

Sometimes Codex prints Incorrect API key provided: sk-proj-**** or Invalid or expired API key because it is silently ignoring your ChatGPT login—or your custom provider key—and sending a different credential altogether.

First, check whether your shell profile (.zshrc, .bashrc, or a direnv .envrc file) is exporting an old OpenAI key into your environment. Run this command to list matching variable names without printing secret keys into your terminal scrollback:

bash
env | grep -E 'OPENAI_API_KEY|CODEX_API_KEY|OPENAI_BASE_URL' | cut -d= -f1

If OPENAI_API_KEY or CODEX_API_KEY appears and you want to use your ChatGPT subscription, remove them from your shell profile and run unset OPENAI_API_KEY CODEX_API_KEY.

Conversely, if you are trying to use an OpenAI Platform API key with the default openai provider, simply running export OPENAI_API_KEY="sk-proj-..." does not work in modern Codex CLI versions (0.146.0+). The default provider reads credentials from ~/.codex/auth.json, not from your shell environment, so an uncached export causes 401 Unauthorized: Missing bearer or basic authentication in header. In addition, the old codex login --api-key flag is deprecated and exits without saving. Always pipe your key into the credential store:

bash
printenv OPENAI_API_KEY | codex login --with-api-key

Custom Provider Traps in ~/.codex/config.toml

If you configure a custom provider or third-party gateway in ~/.codex/config.toml, three configuration mistakes routinely produce deceptive 401 errors:

toml
model = "gpt-6.1-sol"
model_provider = "custom_relay"

[model_providers.custom_relay]
name = "Custom Relay"
base_url = "https://api.example.com/v1"
env_key = "RELAY_API_KEY"
wire_api = "responses"

First, never combine requires_openai_auth = true with env_key in the same [model_providers.<name>] block unless your gateway explicitly reads ~/.codex/auth.json. As clarified in the Codex CLI 0.160.0 documentation, setting requires_openai_auth = true forces Codex to ignore env_key completely and send your cached OpenAI credential instead. Similarly, if you forget the env_key line entirely, Codex falls back to auth.json and sends your OpenAI token to the third-party URL, which promptly rejects it with 401 Invalid or expired API key.

Second, keep model_provider and [model_providers.<name>] inside your global ~/.codex/config.toml file (or ~/.codex/<profile>.config.toml when using --profile). Codex ignores provider definitions placed inside a project-local .codex/config.toml file, falling back to the default OpenAI endpoint while you think you are calling your custom gateway. If CODEX_HOME is set in your environment, run codex doctor to verify which config.toml and auth.json paths Codex is actually loading.

Third, watch how you load env_key into your shell. If you read a key from a file using export RELAY_API_KEY="$(cat ~/key.txt)" and the file ends with a newline, the HTTP client drops the malformed Authorization header altogether and the server returns 401 Unauthorized: You didn't provide an API key. If you load a .env file with a naive xargs command that preserves literal quotation marks around "sk-...", the server receives the quotes as part of the token and returns 401 Invalid or expired API key. Strip both newlines and quotes when exporting:

bash
export RELAY_API_KEY="$(tr -d '\n\r"' < ~/key.txt)"

Unblocking Work Fast: Switching to an API Key or Third-Party Gateway

When OpenAI's ChatGPT authentication pipeline goes down—as it did during the September 25 outage when OpenAI's status page advised Login via API key will unblock access at this time—or when a subscription account gets stuck in a token refresh loop right before a deadline, switching from ChatGPT OAuth to an API key is the fastest way to get back to coding.

Keep in mind what changes when you switch: authenticating with printenv OPENAI_API_KEY | codex login --with-api-key routes traffic through api.openai.com/v1/responses and bills per token at standard API rates rather than using your monthly ChatGPT plan allowance. Once the subscription service recovers, you can switch back at any time by running codex logout and codex login.

If you want a backup route that doesn't depend on OpenAI's direct authentication servers—or if you want to run GPT, Claude, and top open-weight models through a single unified endpoint—you can point Codex and Claude Code at a high-availability gateway like SeedRouter. Because hand-editing ~/.codex/config.toml and ~/.codex/auth.json under pressure is where most developers trigger a new round of 401s (from requires_openai_auth conflicts or stray quotes) and 404s (from missing /v1 path segments), we built a free, open-source desktop tool to handle the switch cleanly. Check out our guide to the LLM API Config GUI for Codex and Claude Code (available for Windows and macOS), which lets you configure your Base URL, API key, and model through a visual interface, toggle between subscription sign-in and third-party relays without corrupting your TOML files, and run a built-in connection check that diagnoses 401, 403, 404, 429, and timeout errors in one click.

Sources and checks

  1. status.openai.com
  2. chatgpt.com
  3. official incident write-up