Home → Help

401 with a key that is definitely correct — check the header format

OpenAI-compatible endpoints expect Authorization: Bearer . If the scheme is missing, duplicated, or the header carries stray whitespace, the server sees a malformed credential and answers 401 — the same response as a wrong key.

What you are seeing

Why it happens

Some HTTP clients and no-code tools ask for a 'token' and add the Bearer prefix themselves. Pasting 'Bearer sk-...' into such a field produces 'Bearer Bearer sk-...'.

Copying from a chat window or a PDF can bring a trailing newline or a non-breaking space. The string looks identical on screen and is not identical on the wire.

A few gateways accept an x-api-key header instead, or in addition. Sending the key in the wrong header is indistinguishable from not sending it at all.

Confirm it is this

Print exactly what your client is sending, with the key length visible:

KEY='paste-here'
echo "length: ${#KEY}"
curl -s -o /dev/null -w '%{http_code}\n' \
  'YOUR_BASE_URL/models' -H "Authorization: Bearer $KEY"

If the length is not what you expect, the copy is the problem. A 200 here with a 401 in your app means the app is building the header differently — inspect what it sends, not what you pasted.

How to fix it

  1. Paste the key only, never the schemeIn any field labelled token, key or secret, paste the key alone. The tool adds Bearer.
  2. Strip whitespace on readTrim the value when you read it from an environment variable or a file. A trailing newline from a heredoc or a copied line is the classic case.
  3. Confirm the key was not rotatedIf the format is right, list your keys in the console and confirm the one in use still exists and is enabled. A revoked key fails exactly like a malformed one.
APICLAN keys start with sk- and go in Authorization: Bearer <key>. A key belongs to one group, so a key that authenticates fine can still 404 on a model outside its group — that is a different error with a different fix.

Related

Unexpected token '<' when calling an OpenAI-compatible API401 invalid API key — when the key looks right but still fails

Last checked 2026-10-01. Written from problems diagnosed on a live OpenAI-compatible gateway, not collected from other sites.