Implement Basic HTTP Authentication in FastAPI
Basic HTTP Authentication is one of the simplest mechanisms for protecting API routes. It sends a Base64-encoded username:password in the Authorization header. Although not secure by itself, when combined with HTTPS it becomes a fast and effective solution for internal tools, microservices, and development environments.
This guide shows you how to implement Basic Auth correctly in FastAPI.
🚀 Full FastAPI Basic Auth Example
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets
app = FastAPI()
security = HTTPBasic()
VALID_USERNAME = "admin"
VALID_PASSWORD = "s3cr3t"
def authenticate(credentials: HTTPBasicCredentials = Depends(security)):
username_ok = secrets.compare_digest(credentials.username, VALID_USERNAME)
password_ok = secrets.compare_digest(credentials.password, VALID_PASSWORD)
if not (username_ok and password_ok):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/secure-basic")
def secure_route(username: str = Depends(authenticate)):
return {"message": f"Hello, {username}. You’re authenticated!"}⸻
Key Notes
1. Never use Basic Auth without HTTPS
Credentials are only Base64 encoded, not encrypted.
2. Use secrets.compare_digest
Prevents timing attacks.
3. Use environment variables or secret managers
Never hard-code credentials in production.
⸻
When to Use Basic Auth
- Internal dashboards
- Health check endpoints
- Development-only routes
- Reverse-proxy protected microservices