LLM API 401 or 403? Fix Authentication and Access Errors
Find why your LLM API rejects a key. Check credentials, endpoints, runtime secrets, and access with one controlled Tokenhot Chat request.

Your API key is saved, the application starts, and the first request comes back unauthorized. Before replacing the key, check three things together: where the request went, which credential the running process supplied, and what operation that credential is allowed to perform.
A 401 points to missing or unacceptable authentication for the requested resource. A 403 means the server understood the request but refused it; that refusal can involve permissions or another restriction. A 403 alone does not prove that authentication succeeded. These are HTTP semantics, not a diagnosis of your particular gateway.
Start with the response your application actually received. Then make the smallest correction the evidence supports.
1. Find the boundary that rejected the request
An LLM application can pass through your backend, a company proxy, an API gateway, and an upstream model provider. Each boundary can apply its own authentication or access rules.
Record the HTTP method, destination host and path, status, content type, and redacted error message. Keep a request ID if one is present. An HTML denial page is a reason to inspect the web server or intermediary; it does not establish that the model provider saw the request.
| What you observe | What to inspect next |
|---|---|
| Every request returns 401 | Runtime secret binding, credential issuer, and authentication header |
| One operation returns 403 while an authorized operation works | Access to the failing endpoint, model, or account scope |
| Local requests work; the deployed service fails | Secret name and binding in that service, deployed revision, and request destination |
| Direct-provider requests work; gateway requests fail | The gateway's own key and documented route |
| The SDK reports an authorization error but the response is HTML | Final URL, application proxy, and intermediary response |
These are starting hypotheses. Preserve the response before changing configuration.
For Tokenhot Chat Completions, the API reference documents POST https://api.tokenhot.ai/v1/chat/completions with Bearer authentication. Its error overview associates 401 with a missing, expired, or invalid key. Use that documented context when investigating this route; don't infer the cause of every 403 from it.
2. Match the credential to the service and protocol
A credential belongs to the service that issued it. If your app calls Tokenhot, use the Tokenhot credential intended for that account. A key that works against a direct provider does not establish access through a gateway, and a gateway key does not become a direct-provider key.
For a client that expects an API base URL, Tokenhot's Quick Start uses https://api.tokenhot.ai/v1. The complete Chat operation URL adds /chat/completions. Inspect what your client constructs: a full operation URL in a base-URL field can produce a duplicated path.
For this Chat route, send one Authorization header whose value is Bearer followed by the raw key. Check for an empty value, surrounding quotes accidentally stored in the secret, a trailing newline, or a duplicated Bearer prefix. Correct the stored value rather than silently trimming an unexpected credential.
Client-specific authentication needs its own setup. If the failure is in Claude Code, follow the Claude Code login and gateway guide; changing a Chat header to x-api-key is not a general fix.
3. Check the process that sends the request
The key in your terminal is not necessarily the key in your deployed application. Confirm that the actual service process receives the expected secret name and a nonempty value. Check the secret manager's binding to the intended service and environment, then restart or redeploy through your normal procedure if that runtime requires it.
Keep the credential out of diagnostics. You usually need to know whether a secret was injected, which named secret/version was selected, and when the process started. You do not need to print the key, a prefix, or a hash into CI logs.
For example, suppose a backend works locally but its production container reads a different environment-variable name. Updating the secret in the dashboard won't fix the mismatch until the application reads that binding. Compare the configured names and deployment revision before rotating a valid key. This is an illustrative configuration failure, not a Tokenhot incident report.
4. Isolate one documented Chat request
Use an existing failed request first. If you need a fresh diagnostic, select one Chat model already confirmed as authorized for your account. A generation request can incur usage charges; run the following only when you have approved that diagnostic usage. It is not a free key-validation endpoint.
This example is an adaptation of the documented request format. It makes a short text request without streaming, tools, or custom options. Supply MODEL_ID and TOKENHOT_API_KEY through your normal environment or secret manager; don't paste a key into source code or shell history.
In a private working directory, prepare the payload with Python:
import json
import os
from pathlib import Path
model = os.environ["MODEL_ID"]
if not model.strip() or model != model.strip():
raise SystemExit("Check the model ID.")
with Path("auth-probe.json").open("x", encoding="utf-8") as f:
json.dump({"model": model, "messages": [
{"role": "user", "content": "Reply with OK."}
]}, f)
Then use Bash, mktemp, and a recent cURL. Use a trusted shell without secret-recording wrappers or debug traps, and disable shell/CI tracing before running it. This block is Bash syntax, not PowerShell syntax.
(
set +x
set +v
umask 077
case ${TOKENHOT_API_KEY-} in
''|*$'\r'*|*$'\n'*) builtin printf '%s\n' 'Set a nonempty, single-line key.' >&2; exit 1 ;;
esac
[ -r auth-probe.json ] || { builtin printf '%s\n' 'Prepare auth-probe.json first.' >&2; exit 1; }
evidence=$(mktemp -d ./auth-probe.XXXXXXXX) || exit 1
if builtin printf 'Authorization: Bearer %s\n' "$TOKENHOT_API_KEY" |
command curl -q --silent --show-error --max-time 30 \
--retry 0 --globoff --proto '=https' \
--request POST 'https://api.tokenhot.ai/v1/chat/completions' \
--header @- --header 'Content-Type: application/json' \
--data-binary @auth-probe.json \
--dump-header "$evidence/response-headers.txt" \
--output "$evidence/response-body.json" \
--write-out '%{http_code}\n'
then rc=0; else rc=$?; fi
builtin printf 'curl_exit=%s evidence=%s\n' "$rc" "$evidence"
exit "$rc"
)
The key reaches cURL through standard input, rather than its command-line arguments. Response files go into a fresh private directory. The cURL manual documents this header input; -q disables default curlrc configuration, and the command sets zero automatic retries and does not follow redirects.
Read the HTTP status separately from curl_exit. Without --fail, a completed HTTP 401 or 403 can still produce cURL exit code 0. A connection failure is not an HTTP rejection. If the request times out, reconcile that attempt before sending another: a timeout does not establish that the server did no work, and rerunning is another potentially billable attempt.
5. Choose the correction from the result
Still 401: verify the raw credential, header, issuer, destination, and runtime binding. Inspect WWW-Authenticate when supplied. Rotate or reissue the key when it is invalid, revoked, exposed, or otherwise requires replacement—not simply because a request failed.
Still 403: inspect the application's error details and the access rules for this account and operation. HTTP 403 can also involve restrictions unrelated to credentials. Ask the service owner to confirm the failing scope. Do not repeatedly resend the unchanged request or try to evade a restriction.
The minimal request succeeds: authentication and access worked for that request at that time. Compare the original application's route, runtime, model ID, and optional features with the minimal request. Restore one feature at a time. This success does not grant access to another endpoint or model.
The response instead names a missing model or channel: compare the exact outgoing model ID and endpoint with the documented operation your account is authorized to use. Preserve the HTTP status, error details, and request ID, then ask support to confirm model access and channel availability if the configuration matches.
Give support a record they can investigate
Send the timestamp and timezone, method and host/path, exact model ID, SDK/client version, status, redacted error details, and request ID if available. Describe the intended account or project and whether another already-authorized operation succeeds. Remove authorization headers, cookies, private prompts, signed URLs, and sensitive account data before sharing.
The useful question is specific: “Is this account allowed to call this model through this endpoint, and which boundary rejected this request?” Once that boundary is identified, you can fix its configuration without cycling through keys or unrelated models.


