# HTTP 401 `invalid_api_key` — API Store Hub

> VI: HTTP 401 xảy ra khi thiếu header xác thực, sai định dạng `Bearer sk-ash-...`, dán thừa dấu cách/xuống dòng, hoặc API key đã bị thu hồi/vô hiệu hóa.
> EN: HTTP 401 occurs when auth headers are missing, malformed, padded with whitespace/newlines, or referencing a revoked API key.

- Canonical VI: https://apistorehub.com/vi/loi-api/401-invalid-api-key-auth
- Canonical EN: https://apistorehub.com/en/loi-api/401-invalid-api-key-auth
- Retry Policy: Never retry HTTP 401; inspect headers, secret trimming, and key status immediately.

## Root Causes
- Omitting the `Bearer ` prefix in the `Authorization` header on OpenAI-compatible endpoints.
- Unloaded `.env` files or accidental trailing whitespace/quotes inside the secret value.
- Using a revoked key or a vendor key instead of a `sk-ash-` gateway key.

## Step-by-Step Resolution
1. Verify the key starts with `sk-ash-` and is Active in Dashboard -> Keys.
2. Use the right header per protocol: `Authorization: Bearer` (OpenAI), `x-api-key` (Anthropic), or `x-goog-api-key` (Gemini).
3. Trim whitespace and `\r\n` line endings when loading secrets from `.env` or secret managers.
4. Run a minimal cURL check against `https://apistorehub.com/v1/models` to isolate environment issues.

## Diagnostic cURL
```bash
curl -i https://apistorehub.com/v1/models \
  -H "Authorization: Bearer sk-ash-your_key"
```

## Production Fix (TypeScript)
```
const rawKey = (process.env.API_KEY || "").trim().replace(/^["']|["']$/g, "");
if (!rawKey.startsWith("sk-ash-")) {
  throw new Error("Invalid API key prefix in environment");
}
```

## FAQ
- **Does one `sk-ash-` key work across OpenAI, Anthropic, and Gemini endpoints?**: Yes. One key authenticates `/v1/chat/completions`, `/v1/messages`, `/v1beta/models`, and `/mcp`.
- **How do I rotate API keys with zero downtime?**: Create a second key, deploy it, confirm traffic shifts over, then disable the old key.
- **Should API keys ever be placed in client-side JavaScript?**: Never. Keep API keys strictly on backend servers and apply per-key spend limits.
