Securing REST API endpoints is a fundamental requirement in any production backend. FastAPI handles authentication cleanly using its built-in **Dependency Injection** system combined with standard **OAuth2 Password Bearer** flows and **JWT (JSON Web Tokens)**.
1. Token Generation and Hashing
from datetime import datetime, timedelta
import jwt
from passlib.context import CryptContext
SECRET_KEY = "YOUR_SUPER_SECRET_KEY"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
2. Current User Dependency Injection
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
if email is None:
raise credentials_exception
return {"email": email}
except jwt.PyJWTError:
raise credentials_exception
3. Protecting API Routes
To protect an endpoint, simply inject Depends(get_current_user) into the route function signature:
@app.get("/api/v1/profile")
async def read_user_profile(current_user: dict = Depends(get_current_user)):
return {"user": current_user, "message": "Protected route accessed successfully"}
Summary
Combining OAuth2PasswordBearer dependencies with JWT token verification ensures clean, declarative security across all your FastAPI routes.
Building secure APIs for your product? Visit my AI integration services or Hire Python Developer.