Good Code
The good version centralizes token extraction and invalid credential handling in a security dependency.
Lesson 05
Use FastAPI security dependencies so auth is declared in the route contract and OpenAPI schema.
from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
# OAuth2PasswordBearer extracts the token and documents the auth scheme.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def current_user(token: Annotated[str, Depends(oauth2_scheme)]):
user = await users.find_by_token(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
)
return userfrom fastapi import APIRouter, Request
router = APIRouter()
@router.post("/reviews/{review_id}/approve")
async def approve_review(review_id: int, request: Request):
# Every route that parses headers itself can drift.
header = request.headers.get("authorization", "")
token = header.replace("Bearer ", "")
user = await users.find_by_token(token)
return await reviews.approve(review_id, user.id)The good version centralizes token extraction and invalid credential handling in a security dependency.
The bad version reparses the header in the route and assumes a user exists. Auth behavior drifts route by route and docs do not show the security scheme.