skip to content

A FastAPI route guarded only by Depends(APIKeyHeader(name="X-API-Key")) accepts any non-empty key: why, and how should the check be built?

level: middleimportance: should knowfreq 40%

answer

  1. extractor versus verifier
  2. the class has no list of valid keys
  3. a dependency that depends on the scheme
  4. constant-time compare, then 401 with challenge
  5. router-level dependencies= so none are missed

basics

~20 s

APIKeyHeader only extracts the header and rejects a missing one; it never compares the value. Wrap it in your own dependency that verifies the key, raises 401 with WWW-Authenticate on a mismatch, and attach that dependency to the router.

solid answer

~40 s

In FastAPI 0.143 `APIKeyHeader` reads `X-API-Key`, raises 401 if it is missing or empty, and otherwise returns the string, whatever it is; it has no idea which keys are valid. The check is a dependency that depends on it, for example `require_partner(key: Annotated[str, Depends(api_key_header)])`, which compares the key with `secrets.compare_digest` on bytes (or looks up a stored digest when there are many keys) and raises `HTTPException(401, headers={"WWW-Authenticate": "APIKey"})` on a mismatch, because FastAPI adds no challenge header to an exception you raise. Keeping the extractor in the chain preserves the missing-key 401 and the Authorize button in `/docs`. Attach `require_partner` with `APIRouter(dependencies=[...])` so every partner route is covered by default, and keep 403 for a valid key that is not allowed to do the operation.

code

python · 27 lines
python
import secrets
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import APIKeyHeader

PARTNER_KEY = "change-me-from-settings"  # load from configuration in a real app

api_key_header = APIKeyHeader(name="X-API-Key")


def require_partner(key: Annotated[str, Depends(api_key_header)]) -> str:
    if not secrets.compare_digest(key.encode(), PARTNER_KEY.encode()):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API key",
            headers={"WWW-Authenticate": "APIKey"},
        )
    return key


app = FastAPI()


@app.post("/partner/orders", dependencies=[Depends(require_partner)])
def create_order() -> dict[str, str]:
    return {"status": "accepted"}

go deeper

for a junior

Remember that the security class only fetches the key; a separate dependency you write has to decide whether it is right.

for a middle

Explain the extractor-then-verifier chain, why the 401 needs headers= for its challenge, and the constant-time comparison.

for a senior

Spot the open route in review, prove it with a made-up key in a test, and move the check to the router so new routes inherit it.

for a principal

Decide where the team's one verifying dependency lives and how routes opt out, so key checking is a default rather than a per-route habit.

## The symptom A route is declared with `dependencies=[Depends(APIKeyHeader(name="X-API-Key"))]`, or with a parameter `key: Annotated[str, Depends(api_key_header)]` that the handler never inspects. A request with no header is rejected with 401, which looks like security. But a request with `X-API-Key: anything` goes straight through. The route is effectively open to anyone who knows the header name, and the header name is published in `/docs`. ## Why it happens `APIKeyHeader` is an **extractor**, not a verifier. Its whole job, in FastAPI 0.143, is: 1. read `request.headers` by the configured `name`; 2. if the value is missing or empty and `auto_error` is `True`, raise 401 `Not authenticated` with `WWW-Authenticate: APIKey`; 3. otherwise return the string. It holds no list of valid keys and has no hook for one. The same is true of `APIKeyQuery`, `APIKeyCookie`, `HTTPBearer` and `HTTPBasic`: each returns the credential the client sent, unchecked. The class name sounds like protection, which is why this mistake survives review. ## What runs on each request With the fix below in place, a request to a partner route goes through these steps before the handler is called: 1. FastAPI resolves the route's dependencies; `require_partner` needs `api_key_header`, so the extractor runs first. 2. `APIKeyHeader` reads `X-API-Key`; a missing or empty header ends the request with its own 401. 3. `require_partner` receives the string and compares it; a mismatch ends the request with your 401. 4. Only then does the handler run, optionally receiving whatever `require_partner` returned. Because FastAPI caches a dependency's result within one request, using `require_partner` both on the router and as a handler parameter does not run the comparison twice. ## Building the check The fix is a **verifying dependency** that depends on the extractor and decides: ```python def require_partner(key: Annotated[str, Depends(api_key_header)]) -> str: if not secrets.compare_digest(key.encode(), PARTNER_KEY.encode()): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key", headers={"WWW-Authenticate": "APIKey"}, ) return key ``` The pieces, and why each is there: - **Depend on the extractor, not on `Request`.** Keeping `APIKeyHeader` in the chain keeps the 401 for a missing key and the `apiKey` scheme in OpenAPI, so the Authorize button in `/docs` still works. - **Compare in constant time.** For a single configured secret, `secrets.compare_digest` on bytes avoids an early-exit comparison; encoding first avoids a `TypeError` if either value contains non-ASCII characters. When there are many keys, look the key up the way the lesson on machine API keys describes (a stored digest, never the plaintext), and return the record. - **Raise 401 with a challenge.** FastAPI does **not** add `WWW-Authenticate` to an `HTTPException` you raise yourself; you pass it in `headers`. Without it the 401 is non-conforming and clients cannot tell which scheme to use. - **Return something useful.** Returning the partner identity lets handlers that declare the dependency as a parameter use it; handlers that only need the gate use `dependencies=[...]`. - **403 is for a different case.** A key that is valid but not allowed to do this operation is authenticated, so a 403 from your own code fits there; an unknown key is a 401. ## Attaching it everywhere it is needed Where the check lives decides how easy it is to forget: | Attachment point | Covers | Typical use | |---|---|---| | `@app.post(..., dependencies=[Depends(require_partner)])` | one path operation | a single protected route | | `APIRouter(dependencies=[Depends(require_partner)])` | every route on that router | a `/partner` router | | `include_router(router, dependencies=[...])` | every route included that way | applying it at composition time | | `FastAPI(dependencies=[...])` | every path operation in the app | rarely; health checks then need a key too | Putting the check on the partner router means a new endpoint added there is protected by default, instead of relying on each author to remember a parameter. ## Reviewing an existing route When auditing a FastAPI service, look for these patterns: - an API key or HTTP security class used directly in `dependencies=[...]` with nothing on top of it; - a handler that receives the key as a parameter and never compares it; - a comparison written with `==` against a hard-coded string; - a 401 raised without `WWW-Authenticate`, or a 403 raised for an unknown key; - the expected key read from source code rather than from settings. A quick test catches the first two: call the route with `TestClient` and a made-up key, and assert 401. If it returns 200, the route is not checking anything.

  • Why not read request.headers directly in require_partner instead of depending on APIKeyHeader?
    It works, but you lose two things the class gives for free: the 401 with `WWW-Authenticate: APIKey` when the header is missing, and the `apiKey` security scheme in OpenAPI that makes `/docs` show an Authorize button. Depending on the class keeps both and leaves only the decision to your code.
  • How would you prove in a test that a route really checks the key?
    Call it with `TestClient` three ways: no header (expect 401 from the class), a made-up key (expect 401 from your dependency, with `WWW-Authenticate: APIKey`), and the configured key (expect 200). The made-up key is the case that catches an extractor used on its own.

APIKeyHeader is a door attendant who turns away anyone with empty hands but never reads the ticket they hold up; checking the ticket is a second person's job, and that person is your dependency.

  • APIKeyHeader rejects keys that are not registered with the FastAPI app
  • FastAPI adds WWW-Authenticate to any 401 HTTPException automatically
  • Comparing the presented key with == is as safe as secrets.compare_digest
  • An unknown key should get 403 Forbidden rather than 401
  • Listing the scheme in app dependencies validates every key on its own