In FastAPI, how do you protect an internal metrics endpoint with HTTPBasic, and what must your own dependency check?
answer
- the browser prompt comes from a challenge
- HTTPBasicCredentials: two str fields
- split at the first colon
- compare_digest on encoded bytes, both fields
- 401 with WWW-Authenticate: Basic again
basics
~10 sHTTPBasic decodes the Authorization header into HTTPBasicCredentials or answers 401 with WWW-Authenticate: Basic. Your dependency compares username and password with secrets.compare_digest on bytes and raises 401 with the same header on a mismatch.
solid answer
~40 s`HTTPBasic(realm="metrics")` is a dependency that reads `Authorization: Basic ...`, base64-decodes it as ASCII, splits at the first colon and returns `HTTPBasicCredentials` with `username` and `password`. A missing or malformed header gets 401 `Not authenticated` with `WWW-Authenticate: Basic realm="metrics"`, which makes a browser show its login prompt. It never checks the values, so you write `get_current_username(credentials: Annotated[HTTPBasicCredentials, Depends(security)])`: encode both fields with `.encode("utf8")`, compare each with `secrets.compare_digest` against values from settings, evaluate both before combining, and raise `HTTPException(401, headers={"WWW-Authenticate": "Basic"})` if either fails, because FastAPI adds no challenge to an exception you raise. Basic sends the password on every request in base64, so serve it only over TLS.
code
python · 34 linesimport secrets
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
METRICS_USER = b"scraper"
METRICS_PASSWORD = b"long-random-value-from-settings"
basic = HTTPBasic(realm="metrics")
def require_metrics_user(
credentials: Annotated[HTTPBasicCredentials, Depends(basic)],
) -> str:
user_ok = secrets.compare_digest(credentials.username.encode("utf8"), METRICS_USER)
password_ok = secrets.compare_digest(
credentials.password.encode("utf8"), METRICS_PASSWORD
)
if not (user_ok and password_ok):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": 'Basic realm="metrics"'},
)
return credentials.username
app = FastAPI()
@app.get("/internal/metrics")
def metrics(user: Annotated[str, Depends(require_metrics_user)]) -> dict[str, int]:
return {"requests_total": 1024}go deeper
Recall the pieces: HTTPBasic, HTTPBasicCredentials with username and password, and the 401 that opens the browser's login prompt.
Walk through what HTTPBasic parses, why the comparison uses compare_digest on bytes with both checks evaluated, and why your 401 needs its header.
Know the edge cases in production: colons in passwords, non-ASCII credentials rejected before your code, TLS as a hard requirement, browser credential caching.
Judge where Basic is acceptable, such as machine-scraped internal endpoints, and where the team needs per-user credentials and an audit trail instead.
## The setting An internal metrics endpoint, scraped by a monitoring job and occasionally opened by an engineer in a browser, needs a username and password and nothing more. **HTTP Basic** fits: the client sends `Authorization: Basic <base64 of username:password>` on every request, and a browser shows its built-in login prompt when the server challenges it. FastAPI's piece of this is `fastapi.security.HTTPBasic`. ## What HTTPBasic does `HTTPBasic` is a callable dependency, like the other security classes. In FastAPI 0.143 its `__call__`: 1. reads the `Authorization` header and splits it at the first space into scheme and parameter; 2. if the header is missing or the scheme is not `basic` (case-insensitively), raises 401 or, with `auto_error=False`, returns `None`; 3. base64-decodes the parameter and **decodes the bytes as ASCII**; a decoding failure raises 401; 4. splits the text at the **first colon** with `partition(":")`; no colon raises 401; 5. returns `HTTPBasicCredentials(username=..., password=...)`, a small Pydantic model of two `str` fields. Every 401 it raises carries `detail` `"Not authenticated"` and `WWW-Authenticate: Basic`, or `Basic realm="metrics"` if you passed `realm="metrics"` to the constructor. That header is what makes a browser open its prompt. Consequences worth knowing: - A password may contain colons: `ops:pa:ss` becomes username `ops`, password `pa:ss`. - A username or password with non-ASCII characters is rejected with 401 by `HTTPBasic` itself, before your code runs. - Steps 3 and 4 raise 401 **even when `auto_error=False`**, because a malformed Basic header is treated as a failed attempt, not as an absent one. ## What your dependency must check `HTTPBasic` checks the format, never the values. The FastAPI docs' recipe is a dependency on top of it: - **Compare both fields with `secrets.compare_digest`** on UTF-8 bytes. An ordinary `==` can return as soon as one character differs, and the docs explain how response time then helps an attacker guess one character at a time. - **Encode before comparing.** `compare_digest` raises `TypeError` when given a `str` with non-ASCII characters, so the docs encode both sides with `.encode("utf8")`; that protects you if the configured value contains such characters, and costs nothing otherwise. - **Evaluate both comparisons before combining them.** The docs' code computes `is_correct_username` and `is_correct_password` first and only then tests `and`, so a wrong username does not skip the password comparison. - **Raise 401 with `WWW-Authenticate: Basic`** (and the realm, if you use one) on a mismatch. FastAPI adds no challenge to an exception you raise, and without it a browser will not prompt again. - **Read the expected values from settings**, never from source code. ## Basic over the wire | Property | What it means for the metrics endpoint | |---|---| | Credentials sent on every request | Nothing to issue or expire, but the password crosses the network each time | | Base64 is an encoding, not encryption | Anyone who sees the request reads the password, so serve it only over TLS | | Browser caches the credentials | Logging out is awkward; acceptable for an internal tool, poor for users | | One shared account | Fine for a scraper; no per-person audit trail | That table is why HTTP Basic suits machine-facing internal endpoints and rarely suits end users. ## Wiring it to the routes Two choices keep the setup tidy: - **One `HTTPBasic` instance per realm.** Create it once at module level and reuse it; the instance holds no request state, only its configuration (`realm`, `scheme_name`, `description`, `auto_error`). - **Attach the verifying dependency where the internal routes live.** If several internal endpoints share the account, put `require_metrics_user` in `APIRouter(dependencies=[...])` for that router, so a new internal route cannot be added unprotected. When a handler needs the username, declare the dependency as a parameter instead, typed `Annotated[str, Depends(require_metrics_user)]`. The browser flow is worth tracing once. The first request carries no header, so `HTTPBasic` answers 401 with the challenge and the browser shows its prompt. The browser then repeats the request with the header. If the password is wrong, your dependency answers 401 with the challenge again, and the prompt reappears; a 401 raised without the header would leave the browser showing the error body instead of a prompt. ## Testing it `fastapi.testclient.TestClient` builds the header for you: `client.get("/internal/metrics", auth=("scraper", "..."))` sends a valid Basic header. Test three cases: no credentials (401 with the realm in `WWW-Authenticate`), a wrong password (401 from your dependency), and the right pair (200).
- What does HTTPBasic return for a password that contains a colon?It splits the decoded text at the first colon only, using `partition(":")`, so `ops:pa:ss` becomes username `ops` and password `pa:ss`. A username therefore cannot contain a colon, which matches the Basic scheme's own rule; a decoded value with no colon at all is rejected with 401.
- Does HTTPBasic(auto_error=False) ever raise?Yes. It returns `None` only when the header is absent or uses another scheme. A header that says `Basic` but holds invalid base64, non-ASCII bytes or no colon still raises 401, because the class treats it as a failed attempt rather than an absent one.
- What is realm for, and do you need it?`realm` is optional text that `HTTPBasic` puts into its challenge, as `WWW-Authenticate: Basic realm="metrics"`. Browsers may show it in the prompt and use it to scope cached credentials. Without it the challenge is plain `Basic`, which works the same.
- HTTPBasic compares the username and password against configured values
- Base64 in the Basic header keeps the password secret without TLS
- Raising a 401 without WWW-Authenticate still makes the browser prompt again
- HTTPBasicCredentials holds the decoded username and password as bytes
- Checking the username first and skipping the password on mismatch is harmless