skip to content

In FastAPI, how does auto_error=False on HTTPBearer let a product page personalise only when a token is present, and what can go wrong?

level: middleimportance: should knowfreq 35%

answer

  1. absence versus invalidity
  2. None instead of a 401
  3. another scheme also yields None
  4. a present token still needs checking
  5. HTTPBasic still rejects a malformed header

basics

~20 s

With auto_error=False, HTTPBearer returns None instead of raising 401 when no Bearer credential is sent, so the page can serve anonymous callers. A token that is present still has to be verified by your dependency, which should reject a bad one.

solid answer

~40 s

Every FastAPI security class takes `auto_error`, default `True`. With `HTTPBearer(auto_error=False)` the dependency returns `None` when the `Authorization` header is missing, empty or uses another scheme, and `HTTPAuthorizationCredentials` otherwise, so you type it `HTTPAuthorizationCredentials | None` and treat `None` as an anonymous caller. The flag covers absence only: a forged or expired token is still returned unchecked, so your dependency verifies it and should raise 401 with `WWW-Authenticate: Bearer` rather than quietly fall back to anonymous, or an expired session degrades without the client ever knowing. Watch two traps: `HTTPBasic(auto_error=False)` still raises 401 for a malformed Basic header, and the operation keeps its security requirement in OpenAPI, so `/docs` shows it locked.

code

python · 33 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

KNOWN_TOKENS = {"token-ada": "ada"}  # stand-in for real token verification

optional_bearer = HTTPBearer(auto_error=False)


def optional_user(
    creds: Annotated[HTTPAuthorizationCredentials | None, Depends(optional_bearer)],
) -> str | None:
    if creds is None:
        return None  # no Bearer credential: serve the anonymous page
    user = KNOWN_TOKENS.get(creds.credentials)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return user


app = FastAPI()


@app.get("/products/{product_id}")
def product_page(
    product_id: int, user: Annotated[str | None, Depends(optional_user)]
) -> dict[str, object]:
    return {"product_id": product_id, "recommended_for": user}

go deeper

for a junior

Remember that auto_error=False turns the missing-credential 401 into None, and that the parameter's type should allow None.

for a middle

Explain exactly which requests yield None for HTTPBearer, and why a present token still has to pass your own verification.

for a senior

Defend raising 401 for a bad token on an optional endpoint, and know the HTTPBasic malformed-header exception and the silent scheme mismatch.

for a principal

Set the team rule for optional endpoints: which failures downgrade to anonymous, which return 401, and how that is documented and tested.

## The goal: optional authentication A product page should work for everyone, and add personal recommendations when the caller is signed in. In FastAPI that means a dependency that yields **a user or `None`**, rather than one that rejects the request. Every security class in `fastapi.security` supports this through one constructor argument: **`auto_error`**, which defaults to `True`. ## What auto_error=False changes With the default, a missing credential raises the class's 401 before the endpoint runs. With `auto_error=False`, the same situation makes the dependency **return `None`**. For `HTTPBearer(auto_error=False)` in FastAPI 0.143, `None` comes back when: - there is no `Authorization` header; - the header has a scheme but no credentials, such as `Authorization: Bearer` alone; - the scheme is something other than `Bearer` (compared case-insensitively), such as `Authorization: Basic ...`. Otherwise it returns `HTTPAuthorizationCredentials` with `scheme` and `credentials`. Type the parameter as `HTTPAuthorizationCredentials | None` so the annotation tells the truth. The API key classes behave the same way: a missing or empty key returns `None`. ## What auto_error=False does not change The flag is about **absence**, not validity. Two consequences follow: 1. **A present credential is still unchecked.** `HTTPBearer` returns `"forged"` just as readily as a real token. Your dependency must verify it, exactly as in the required case. 2. **You must decide what an invalid credential means.** The class cannot decide for you. | Request | `HTTPBearer(auto_error=False)` returns | Sensible outcome | |---|---|---| | No `Authorization` header | `None` | anonymous page | | `Authorization: Basic ...` | `None` | anonymous page | | `Bearer` with a valid token | credentials | personalised page | | `Bearer` with an expired or forged token | credentials | 401 from your dependency | The last row is the design choice that matters. Returning `None` for a bad token looks friendly, but a signed-in user whose token expired silently sees the anonymous page, and the client never learns it should refresh. Raising `HTTPException(401, headers={"WWW-Authenticate": "Bearer"})` tells it. ## Where it surprises people - **HTTPBasic is not fully optional.** `HTTPBasic(auto_error=False)` returns `None` for a missing header or another scheme, but a header that says `Basic` and holds invalid base64, non-ASCII bytes or no colon **still raises 401**. The class treats a malformed attempt as a failed one. - **The scheme mismatch is silent.** A client that sends the wrong scheme gets the anonymous page with no error. That is correct for optional auth, but it hides client bugs, so log it if it matters. - **The docs still show a lock.** The operation keeps its security requirement in the generated OpenAPI document, so `/docs` shows it as protected even though anonymous calls work; say so in the operation's description. - **Forgetting to verify** turns optional auth into "anyone who sends any token is that user", if the handler trusts a claim read straight from the credentials. ## Several optional schemes in one dependency The `auto_error` docstrings name a second use: accepting a credential in one of several places. Declare each scheme with `auto_error=False` and decide in one dependency: ```python def caller( key: Annotated[str | None, Depends(APIKeyHeader(name="X-API-Key", auto_error=False))], bearer: Annotated[HTTPAuthorizationCredentials | None, Depends(HTTPBearer(auto_error=False))], ): if key is None and bearer is None: raise HTTPException(401, "Not authenticated", headers={"WWW-Authenticate": "Bearer"}) ... ``` Both schemes then appear in OpenAPI as alternative requirements, and the decision about which one wins, and what to do when both are present, lives in one place you can test. ## Testing the optional dependency An optional dependency has more branches than a required one, and each needs a test with `TestClient`: 1. no `Authorization` header: 200 with the anonymous response; 2. a valid Bearer token: 200 with the personalised response; 3. a forged or expired token: 401 with `WWW-Authenticate: Bearer`; 4. another scheme, such as `Basic ...`: 200 anonymous, which documents that the downgrade is intended. The fourth test is the one teams skip, and it is the one that tells a reader the silent fallback is a decision rather than an accident.

  • Why raise 401 for a bad token on an endpoint that works anonymously?
    Because the caller tried to authenticate and failed. If the dependency returns `None`, a user whose token expired silently gets the anonymous page and the client has no signal to refresh or sign in again. A 401 with `WWW-Authenticate: Bearer` makes the failure visible; callers who send nothing are unaffected.
  • Does auto_error=False change what /docs shows for the operation?
    No. The scheme is still registered and the operation still lists it as a security requirement in the generated OpenAPI document, so Swagger UI shows the lock. If anonymous use is intended, state it in the operation's description.

  • With auto_error=False HTTPBearer rejects forged tokens and returns None for them
  • HTTPBasic with auto_error=False never raises, whatever the client sends
  • A wrong Authorization scheme makes HTTPBearer(auto_error=False) raise 401
  • Falling back to anonymous on an expired token is always the friendlier choice
  • auto_error=False marks the operation as public in the OpenAPI document