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.

4 min readUpdated 2026-11-30
In This Lesson
  • 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:

text
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 CaseExpected Error / ReturnWhy
No Authorization header401 UnauthorizedClient sent no credentials
Authorization: Basic xyz or Bearer 401 UnauthorizedWrong scheme or empty token
Tampered signature or expired exp401 UnauthorizedToken cannot be trusted
Valid token with "role": "student"403 ForbiddenIdentity verified, insufficient privileges
Valid token with "role": "admin"Returns payload dictBoth 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:

python
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 user

3. Your Mission & Edge Cases to Handle

Implement the two TODO functions in the playground:

  1. 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 ", raise AuthError(401, "Missing Bearer token").
    • Strip "Bearer " and whitespace; if the remaining token string is empty ("Bearer "), also raise AuthError(401, "Empty Bearer token").
    • Return the extracted token string.
  2. 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-time hmac.compare_digest signature and exp > time.time()). If None, raise AuthError(401, "Invalid or expired token").
    • Check if payload.get("role") != "admin": and raise AuthError(403, "Admin access required").
    • Otherwise return payload.
Never Confuse 401 and 403—or Trust Unverified Payloads
  • Always call verify_token(token) before reading payload.get("role"). Otherwise an attacker can craft a fake Base64 payload with "role": "admin" and a garbage signature!
  • Return 401 whenever identity cannot be proven (missing/tampered/expired token). Return 403 only when identity is proven, but the user's role lacks permission.

4. Interactive Lab Sandbox

Python 3Lab 2: Bearer Auth & 401/403 Role Guard
Output

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({})) raises AuthError with status_code == 401.
  • Non-Bearer header ({"Authorization": "Basic abc123"}) raises 401.
  • Tampered token (admin_tok[:-4] + "0000") raises 401.

Lab 2 Completion Checklist

0/3 done