OpenAI 401 Invalid Authentication (invalid_api_key)
OpenAI returns 401 with invalid_api_key when the Authorization header token doesn't match any active key. In 2026, the split between user-scoped, project-scoped, and service account keys makes this more common — a key that works locally may be scoped to the wrong project in production.
Why it happens
OpenAI uses Bearer token authentication in the Authorization header. A 401 with invalid_api_key means the token doesn't match any active key in OpenAI's system. Three modern causes: (1) whitespace in the key (same issue as every provider), (2) project scope mismatch — since project keys became the primary path in 2025, keys scoped to one project fail when used against another project's endpoint, (3) key rotation without redeployment. The 2025 deprecation of user-scoped keys in favor of project-scoped keys means many teams still have a mix of key types, and confusion about which key belongs to which project is a leading cause of production 401s.
Three ways to fix it
Fix 1Verify the key format and length
Legacy user keys start with sk-. Modern project keys start with sk-proj-. Service account keys have their own format. Compare what you have to what your OpenAI Console shows for the target project.
import os
key = os.environ.get("OPENAI_API_KEY", "")
print(f"Length: {len(key)}")
print(f"Prefix: {key[:8]!r}")
# sk-proj-... indicates project-scoped (recommended)
# sk-svcacct-... indicates service account
# sk-... (short prefix) is legacy user key — should migrate
if key.startswith("sk-proj-"):
print("Type: project-scoped")
elif key.startswith("sk-svcacct-"):
print("Type: service account")
elif key.startswith("sk-"):
print("Type: LEGACY user-scoped (migrate to project)")
else:
print("Type: UNKNOWN — check format")Fix 2Confirm the key belongs to the target project
Every OpenAI request routes to a specific project. A project-scoped key only works for its own project. Set the OpenAI-Project header explicitly to match the key's project ID.
from openai import OpenAI
client = OpenAI(
api_key=os.environ["OPENAI_API_KEY"],
project="proj_XXXXXXXXXXXXXXXXXXX", # Match the key's project
organization="org_XXXXXXXXXXXXXXXXXX" # Also required for multi-org
)
response = client.chat.completions.create(
model="gpt-5-6",
messages=[{"role": "user", "content": "ping"}],
max_completion_tokens=10
)Fix 3Rotate the key in the OpenAI Console
Go to platform.openai.com/api-keys. Create a new project-scoped key. Deploy alongside the old key. Verify production uses the new key. Only then revoke the old key. This dual-key window enables zero-downtime rotation.
# Test the new key before removing the old one:
from openai import OpenAI
new_client = OpenAI(api_key="sk-proj-NEW_KEY_HERE")
try:
resp = new_client.chat.completions.create(
model="gpt-5-6", max_completion_tokens=5,
messages=[{"role": "user", "content": "ping"}]
)
print(f"New key works: {resp.id}")
except Exception as e:
print(f"New key failed: {e}") # Do NOT revoke old key yetPreventing it going forward
- Migrate all legacy user-scoped keys (
sk-...) to project-scoped keys (sk-proj-...). User-scoped keys are deprecated and will be removed. - Store keys in a secret manager with per-environment separation. Never commit keys to git or share via chat.
- Rotate project keys every 90 days at minimum. Rotate immediately on any exposure incident (logs, screenshots, error reports).
- On startup, print the key type (project / service account / legacy) and last 4 characters so environment misconfigurations surface quickly.
- Use service account keys for automated workflows and CI/CD, not personal user-linked project keys.
- Set spending limits per project in the OpenAI dashboard. Cap unexpected usage on leaked keys.
- Configure logger redaction for patterns matching
sk-proj-*,sk-svcacct-*, andsk-*to prevent accidental key exposure in logs.
Frequently asked questions
Why did my key work yesterday but fail today?
Two common causes: (1) another team member rotated it in the Console without updating deployments, (2) OpenAI expired a legacy user-scoped key as part of the ongoing user→project migration.
What's the difference between a project key and a service account key?
Project keys are scoped to a specific project and can be created by any project member. Service account keys are tied to a service account entity (for automation), don't belong to a user, and survive user offboarding. Prefer service account keys for production.
Can I use one project key across multiple projects?
No. Project keys are strictly scoped to one project. If you need multi-project access, use service accounts with membership in multiple projects, or use a separate key per project.
Does the Organization ID header still matter with project keys?
Yes for orgs with multiple projects across multiple organizations. The OpenAI-Organization header disambiguates which org context the request runs in. Single-org accounts don't need it.
How do I audit which key made a specific request?
OpenAI's usage dashboard shows per-key usage. For per-request auditing, log the last 4 chars of the key used in your application, and correlate with dashboard entries by timestamp and model.