4. Authentication, Security & Configuration
Practice Lab 2: Request Auth Guard & Token Validation
Put Modules 3 and 4 into practice: implement Bearer header extraction, signed token verification with expiration checks, and role-based 401/403 authorization guards.
- Parse and validate `Authorization: Bearer <token>` headers cleanly
- Distinguish 401 Unauthorized (invalid/expired token) from 403 Forbidden (insufficient role)
- Verify every auth edge case with automated assert tests
In this lab, you will build a clean authentication & authorization guard—the exact logic FastAPI's Depends(get_current_user) and Depends(require_admin) execute before a protected endpoint runs!
1. Architecture: Where Auth Guards Sit in the Lifecycle
Every request to an admin endpoint (such as DELETE /courses/42) passes through two sequential gates before touching the database:
Incoming HTTP Headers
│
▼
1. Authentication (`extract_bearer_token` + `verify_token`)
├─ Missing header, non-Bearer scheme, bad HMAC, or expired? ──▶ 401 Unauthorized
└─ Valid signature & unexpired `exp`!
│
▼
2. Authorization (`require_admin`)
├─ `payload.get("role") != "admin"`? ──▶ 403 Forbidden
└─ Role is `"admin"` ──▶ Return `payload` to route handler!Status Code Decision Matrix
| Request Case | Expected Error / Return | Why |
|---|---|---|
No Authorization header | 401 Unauthorized | Client sent no credentials |
Authorization: Basic xyz or Bearer | 401 Unauthorized | Wrong scheme or empty token |
Tampered signature or expired exp | 401 Unauthorized | Token cannot be trusted |
Valid token with "role": "student" | 403 Forbidden | Identity verified, insufficient privileges |
Valid token with "role": "admin" | Returns payload dict | Both authentication and authorization pass |
2. How This Maps to FastAPI Depends()
In a FastAPI app, you wire this guard cleanly using Header() and nested Depends()—so protected routes never repeat header parsing:
def get_current_user(authorization: str | None = Header(default=None)) -> dict:
... # Raises HTTPException(401) if missing/invalid/expired
def require_admin(user: dict = Depends(get_current_user)) -> dict:
if user.get("role") != "admin":
raise HTTPException(status_code=403, detail="Admin access required")
return user3. Your Mission & Edge Cases to Handle
Implement the two TODO functions in the playground:
-
extract_bearer_token(headers: dict[str, str]) -> str- HTTP header names are case-insensitive (
"Authorization"vs"authorization"): scan keys with.lower() == "authorization". - If missing or not starting with
"Bearer ", raiseAuthError(401, "Missing Bearer token"). - Strip
"Bearer "and whitespace; if the remaining token string is empty ("Bearer "), also raiseAuthError(401, "Empty Bearer token"). - Return the extracted token string.
- HTTP header names are case-insensitive (
-
require_admin(headers: dict[str, str]) -> dict- Extract the token using
extract_bearer_token(headers). - Verify it with
verify_token(token)(which checks the constant-timehmac.compare_digestsignature andexp > time.time()). IfNone, raiseAuthError(401, "Invalid or expired token"). - Check
if payload.get("role") != "admin":and raiseAuthError(403, "Admin access required"). - Otherwise return
payload.
- Extract the token using
- Always call
verify_token(token)before readingpayload.get("role"). Otherwise an attacker can craft a fake Base64 payload with"role": "admin"and a garbage signature! - Return
401whenever identity cannot be proven (missing/tampered/expired token). Return403only when identity is proven, but the user's role lacks permission.
4. Interactive Lab Sandbox
Click “Run Code” to execute this snippet right in your browser.
5. Extra Edge Cases to Verify
Once the commented assertions pass, verify these additional attack/failure scenarios in the playground:
- Missing header (
require_admin({})) raisesAuthErrorwithstatus_code == 401. - Non-Bearer header (
{"Authorization": "Basic abc123"}) raises401. - Tampered token (
admin_tok[:-4] + "0000") raises401.