
FastAPI
Basic authentication sends username and password with each request encoded in Base64. Simple but requires HTTPS for security.
Credentials are encoded and sent in the Authorization header:
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets
app = FastAPI()
security = HTTPBasic()
@app.get("/basic")
async def basic_auth(credentials: HTTPBasicCredentials = Depends(security)):
correct_username = secrets.compare_digest(credentials.username, "user")
correct_password = secrets.compare_digest(credentials.password, "pass")
if not (correct_username and correct_password):
raise HTTPException(status_code=401, detail="Invalid credentials")
return {"message": f"Hello {credentials.username}"}from fastapi.security import HTTPBasic, HTTPBasicCredentials
security = HTTPBasic()
async def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
# Check against database
user = authenticate_user(credentials.username, credentials.password)
if not user:
raise HTTPException(status_code=401, detail="Invalid credentials")
return user
@app.get("/protected")
async def protected(user: dict = Depends(get_current_user)):
return {"user": user}from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str):
return pwd_context.hash(password)
def verify_password(plain, hashed):
return pwd_context.verify(plain, hashed)Basic auth is suitable for:
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward