Brute Force Attack in Fastapi with Basic Auth
Brute Force Attack in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability
A brute force attack against a FastAPI endpoint protected with HTTP Basic Auth involves systematically submitting many username and password combinations to guess valid credentials. Because Basic Auth transmits credentials in an easily decoded Base64 format, an attacker who can observe or intercept traffic gains immediate access if the connection lacks encryption. FastAPI does not inherently throttle authentication attempts at the framework level, so an unprotected route will accept repeated requests without delay, enabling automated tools to iterate through credential lists rapidly.
When combined with unauthenticated or weakly rate-limited endpoints, this pattern becomes especially risky. For example, an API that exposes user enumeration behavior—returning different status codes or messages for existing versus non-existing users—helps an attacker refine guesses without triggering suspicion. The absence of account lockout, captchas, or exponential backoff further reduces the cost of each attempt. Even if TLS encrypts traffic, the server-side application must still enforce strict controls; otherwise, leaked credentials from other sources can be rapidly tested against the FastAPI service.
Consider a scenario where a FastAPI route uses Basic Auth but relies solely on the transport layer for protection. A scanner testing this surface will detect the authentication method, attempt credential permutations, and evaluate whether the endpoint responds differently to valid inputs. Findings may highlight missing rate limiting, predictable user accounts, and lack of multi-factor controls, all of which amplify the risk of successful brute force activity. This aligns with common techniques observed in credential stuffing and password spraying campaigns that target weak authentication boundaries.
Basic Auth-Specific Remediation in Fastapi — concrete code fixes
To harden FastAPI against brute force attacks when using HTTP Basic Auth, combine secure credential handling with explicit rate controls and resilient validation logic. The following example demonstrates a robust implementation using HTTPBasic from fastapi.security, a constant-time comparison, and integration with a rate limiter to restrict attempts per client identifier.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.middleware import Middleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
import secrets
import hashlib
app = FastAPI()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(429, _rate_limit_exceeded_handler)
security = HTTPBasic()
# Secure credential store (in practice, use a database with salted hashes)
USERS = {
"alice": hashlib.pbkdf2_hmac("sha256", b"CorrectHorseBatteryStaple", b"alice_salt", 100000).hex()
}
def verify_user(credentials: HTTPBasicCredentials = Depends(security)):
expected_hash = USERS.get(credentials.username)
if expected_hash is None:
# Use a constant-time comparison to avoid timing leaks even when user is unknown
dummy_hash = hashlib.pbkdf2_hmac("sha256", b"dummy", b"dummy_salt", 100000).hex()
secrets.compare_digest(dummy_hash, dummy_hash)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"}
)
if not secrets.compare_digest(expected_hash, hashlib.pbkdf2_hmac("sha256", credentials.password.encode("utf-8"), credentials.username.encode("utf-8"), 100000).hex()):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"}
)
return credentials.username
@app.get("/secure", dependencies=[Depends(limiter.limit("5/minute"))])
def protected_route(username: str = Depends(verify_user)):
return {"message": f"Hello, {username}"}
This pattern enforces per-IP rate limiting, avoids user enumeration through constant-time operations, and stores passwords as salted hashes rather than plaintext or reversible forms. For broader protection, integrate middleware or gateway-level throttling and monitor authentication failure patterns to detect ongoing brute force campaigns. When scanning such endpoints with tools that support OpenAPI/Swagger analysis, ensure the spec accurately reflects these security constraints so runtime tests align with intended defenses.