Broken Authentication in Fastapi with Api Keys
Broken Authentication in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
Using API keys in FastAPI can reduce authentication friction, but when implemented without strict validation and scope controls it can lead to Broken Authentication. A key is often stored as a plain string, passed via query parameters or headers, and compared with a simple equality check. If the comparison is not constant-time, an attacker can perform timing side-channel attacks to learn valid keys. FastAPI’s dependency injection and route handlers make it easy to forget to enforce key rotation, scope restrictions, or revocation checks, which means an exposed key remains valid indefinitely.
In many integrations, keys are passed in HTTP headers like X-API-Key. If the application does not enforce HTTPS, keys can leak in transit or via server logs. MiddleBrick’s Authentication check flags missing transport-layer enforcement and weak validation logic. Because API keys are bearer credentials, any leak grants the same access as a legitimate user. When combined with missing authorization checks (e.g., missing scope validation per endpoint), a compromised key can lead to privilege escalation or access to sensitive data, which maps to BOLA/IDOR and BFLA findings in the scan.
Another common mistake is storing keys in source code or environment variables without restricting access at the runtime level. FastAPI applications deployed in shared environments or containers may inadvertently expose these variables, enabling unauthorized key reuse. The scanner tests unauthenticated endpoints to see whether a valid API key is required; missing enforcement shows up as a high-severity Authentication finding. Because keys are static by design, they lack the granularity of OAuth scopes or short-lived tokens, increasing the blast radius if leaked.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To reduce risk, enforce HTTPS for all routes, use constant-time comparison, and scope keys to specific endpoints. Store keys outside the application source, and rotate them on a schedule. Below is a minimal, secure FastAPI pattern using dependency injection for API key validation:
from fastapi import Depends, FastAPI, Header, HTTPException, status
from typing import Optional
import secrets
import hmac
app = FastAPI()
# Store hashed keys in a secure vault or environment; for example:
VALID_KEYS = {
"sha256$7b3d...": "read:data", # key_id -> scope
"sha256$1a9f...": "read:data write:data",
}
def verify_api_key(key: Optional[str] = Header(None)):
if not key:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="API key missing")
# Use a constant-time comparison to avoid timing leaks
for stored_key_hash, scope in VALID_KEYS.items():
# In production, use a slow hash and store only the hash
if hmac.compare_digest(stored_key_hash, hash_key(key)):
return {"key_id": stored_key_hash, "scope": scope}
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API key")
def hash_key(raw_key: str) -> str:
# Placeholder: use a real key derivation in production
import hashlib
return f"sha256${hashlib.sha256(raw_key.encode()).hexdigest()}"
@app.get("/data")
async def read_data(identity: dict = Depends(verify_api_key)):
# Optionally check scope before returning data
if "read:data" not in identity["scope"].split():
raise HTTPException(status_code=403, detail="Insufficient scope")
return {"message": "secure data"}
@app.post("/update")
async def update_data(identity: dict = Depends(verify_api_key)):
if "write:data" not in identity["scope"].split():
raise HTTPException(status_code=403, detail="Insufficient scope")
return {"status": "updated"}
Additional remediation steps include enforcing key rotation, limiting key usage by IP or user-agent, and using middleware to reject requests with malformed keys. MiddleBrick’s CLI can verify these changes by scanning your FastAPI service; the CLI command is middlebrick scan <url>. For teams managing many services, the Pro plan supports continuous monitoring and CI/CD integration so that any regression in authentication posture can be caught before deployment.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |