Denial Of Service in Fastapi with Basic Auth
Denial Of Service in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability
Denial of Service (DoS) in FastAPI when Basic Authentication is used can arise from the interaction between authentication handling and resource-intensive request processing. Basic Auth requires the server to parse the Authorization header, decode the base64-encoded credentials, and validate them on each request. If validation is performed synchronously or with an inefficient lookup, CPU and memory usage can spike under high concurrency, leading to thread or event-loop blocking. This is especially relevant when the authentication backend performs slow operations such as repeated database queries or password hashing without concurrency limits.
Another DoS angle specific to Basic Auth in FastAPI is the lack of built-in rate limiting on the authentication endpoint or resource. Without explicit limits, an attacker can send many requests with invalid credentials, forcing the server to perform costly hash verifications or user lookups. In a synchronous implementation, this can exhaust worker processes or thread pools; in an async implementation, it can saturate the event loop. The unauthenticated scan capabilities of middleBrick include Rate Limiting and Authentication checks, which can surface these risks by detecting missing or weak throttling around auth-sensitive paths.
Additionally, malformed or oversized credentials or missing constraints on request body size can amplify resource consumption when Basic Auth is used. For example, if the server attempts to parse large payloads while also validating auth on each route, memory pressure increases. The combination of per-request auth validation and inefficient resource controls can degrade response times or cause timeouts, aligning with findings such as BFLA/Privilege Escalation when auth checks are bypassed and Input Validation when size and format constraints are missing. middleBrick’s 12 security checks run in parallel, testing these unauthenticated surfaces and highlighting DoS-prone configurations before they are exploited in production.
Basic Auth-Specific Remediation in Fastapi — concrete code fixes
To mitigate DoS risks with Basic Auth in FastAPI, apply targeted fixes that reduce per-request cost and enforce usage controls. Use dependency injection efficiently, cache validated credentials where appropriate, and enforce rate limiting at the route or global level. The following examples demonstrate secure patterns.
Example 1: Efficient Basic Auth dependency with cached user validation
import base64
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing import Dict
app = FastAPI()
security = HTTPBasic()
# Simulated user store; in production, use a fast cache like Redis or an optimized DB lookup
USERS_DB: Dict[str, str] = {
"alice": "securepassword123", # In real apps, store only hashes
}
def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
token = credentials.password.decode("utf-8") if isinstance(credentials.password, bytes) else credentials.password
expected_password = USERS_DB.get(credentials.username)
if expected_password is None or expected_password != token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/items/")
async def read_items(user: str = Depends(get_current_user)):
return {"message": f"Hello, {user}"}
Example 2: Adding rate limiting with slowapi to protect auth-sensitive endpoints
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.middleware import SlowAPIMiddleware
app = FastAPI()
security = HTTPBasic()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(429, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
USERS_DB = {"alice": "securepassword123"}
def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
expected = USERS_DB.get(credentials.username)
if not expected or expected != credentials.password.decode("utf-8"):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": "Basic"})
return credentials.username
@app.get("/secure/", dependencies=[Depends(limiter.limit("5/minute"))])
async def secure_endpoint(user: str = Depends(get_current_user)):
return {"data": "protected"}
General recommendations
- Use asynchronous password hashing checks or pre-hashed comparisons to avoid blocking the event loop.
- Apply rate limiting to authentication routes and sensitive endpoints; the middleBrick Pro plan supports CI/CD integration to enforce thresholds automatically in pipelines.
- Validate input size early and reject overly large Authorization headers before processing.
- Instrument monitoring to detect abnormal authentication failure rates, which can indicate DoS or credential-testing attempts.
These changes reduce CPU cycles per request and prevent unthrottled authentication checks from becoming a vector for resource exhaustion. For continuous assurance, integrate the middleBrick CLI or GitHub Action to scan your FastAPI endpoints regularly and track security scores over time via the dashboard.
Related CWEs: resourceConsumption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-400 | Uncontrolled Resource Consumption | HIGH |
| CWE-770 | Allocation of Resources Without Limits | MEDIUM |
| CWE-799 | Improper Control of Interaction Frequency | MEDIUM |
| CWE-835 | Infinite Loop | HIGH |
| CWE-1050 | Excessive Platform Resource Consumption | MEDIUM |