Skip to content

Lesson 4 of 9 · 25m

Authentication and Authorization Without the Confusion

Separate identity from permission, validate JWTs correctly, model scopes and tenant access explicitly, and avoid the common FastAPI auth footguns.

The first thing to teach a new hire is that authentication and authorization are different problems. Authentication answers 'who are you?' Authorization answers 'what may you do?' Most API breaches happen when those answers are smeared together into one dependency that returns a user object and everyone assumes the hard part is done.

Authenticate at the edge, authorize at the decision point

A typical bearer-token dependency establishes identity:

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

bearer = HTTPBearer(auto_error=False)

def current_principal(
    creds: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> Principal:
    if creds is None:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
    return validate_token(creds.credentials)

That principal is evidence of identity, not permission. Endpoints and service functions still need explicit checks: does this user own this project, belong to this tenant, or hold this scope?

Validate JWT claims like you mean it

A JWT is not trustworthy because it parses. Validate signature, issuer, audience, expiry, nbf, and key ID against the expected keys. If you use asymmetric keys and rotation, fetch keys from a controlled JWKS cache rather than trusting arbitrary embedded URLs.

The catastrophic anti-pattern is accepting alg=none or confusing algorithm families. Pin the algorithm; do not let the token choose one.

Scopes are coarse, ownership is fine-grained

OAuth scopes such as projects:read are useful coarse gates:

def require_scope(scope: str):
    def checker(principal: Principal = Depends(current_principal)) -> Principal:
        if scope not in principal.scopes:
            raise HTTPException(status.HTTP_403_FORBIDDEN, "insufficient scope")
        return principal
    return checker

But a scope does not prove the project belongs to the caller. Combine both:

project = get_project_or_404(db, project_id)
if project.tenant_id != principal.tenant_id:
    raise HTTPException(status.HTTP_404_NOT_FOUND, "project not found")

Returning 404 instead of 403 can avoid confirming existence across tenants — decide this deliberately.

Beware confusing middleware and dependencies

Middleware sees every request but lacks route-specific context. Dependencies know the route but run inside FastAPI's dispatch. Use middleware for cross-cutting concerns such as request IDs, auth token extraction if truly global, or security headers. Use dependencies for identity and permission decisions that vary per route.

Sessions and cookies need browser defenses

If this API is consumed by browsers with cookies rather than bearer tokens, CSRF protection is mandatory. SameSite helps but is not a complete authorization model. Prefer bearer tokens for pure APIs; if cookies are required, use strict origin checks plus CSRF tokens and never accept credentials cross-origin by accident.

Field notes

  • A valid token proves authentication, never object-level authorization.
  • Cache JWKS keys, but respect key rotation and expiry; fetching keys per request is an outage waiting to happen.
  • Log authorization failures without logging bearer tokens or secrets.
  • Machine-to-machine credentials deserve narrower scopes and shorter lifetimes than human sessions.

Was this lesson helpful?

Sign in to rate