Skip to content

401 Unauthorized: Incorrect API key provided - Codex

Quick fix

After switching to OpenAI Official or turning the proxy off, clear the leftover third-party OPENAI_API_KEY from ~/.codex/auth.json and restart Codex.

Error output
401 Unauthorized: Incorrect API key provided: 9bea28a1***3WBS

When switching provider in cc-switch — from a third-party channel such as Zhipu GLM to OpenAI Official, for example — or when the proxy is turned off unexpectedly, the tool fails to backfill the request address correctly or to clear the previous provider's OPENAI_API_KEY from ~/.codex/auth.json.

Codex then reads the leftover third-party API key and sends it to the official endpoint (https://api.openai.com/v1/responses), so the credentials and the target endpoint do not match. The OpenAI Official preset is meant to use OAuth authentication (requires_openai_auth = true) and needs no API key, hence the 401.

  1. Open the ~/.codex/auth.json file by hand.

  2. Delete or clear the leftover third-party OPENAI_API_KEY field, setting it to null or removing it entirely.

    // ~/.codex/auth.json
    {
    "auth_mode": "chatgpt",
    "OPENAI_API_KEY": null,
    "tokens": {
    "id_token": "xxxx",
    "access_token": "xxx",
    "refresh_token": "xxxx",
    "account_id": "xxx"
    }
    }
  3. Restart Codex or the Codex App to trigger the official ChatGPT OAuth login flow.

  4. If the problem came from the proxy being turned off unexpectedly, try turning the proxy on once more in cc-switch so the request address is backfilled correctly. If repeating that does not help, use the manual config file cleanup above.

ToolCodex
Version3.16.1
PlatformsWindows
What is this backfilled request address, and what if toggling the proxy repeatedly does not help?
If toggling the proxy repeatedly does not help, the local config file is already mismatched. Clear the leftover OPENAI_API_KEY from ~/.codex/auth.json by hand and restart the app to recover.

This is an unofficial community wiki with no affiliation to the cc-switch authors or the project itself. Its content is compiled from the project's public GitHub issues. This site distributes no software.