python 50 lines · 7 steps

JWT bearer auth as a FastAPI dependency

A reusable dependency that validates a bearer token and hands routes a typed current user.

Explained by highlit
1import os
2from datetime import datetime, timezone
3 
4import jwt
5from fastapi import Depends, HTTPException, status
6from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7from pydantic import BaseModel
8 
9JWT_SECRET = os.environ["JWT_SECRET"]
10JWT_ALGORITHM = "HS256"
11JWT_AUDIENCE = "api://internal"
12 
13bearer_scheme = HTTPBearer(auto_error=True)
14 
15 
16class CurrentUser(BaseModel):
17 id: str
18 email: str
19 scopes: list[str] = []
20 
21 
22def get_current_user(
23 credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
24) -> CurrentUser:
25 try:
26 payload = jwt.decode(
27 credentials.credentials,
28 JWT_SECRET,
29 algorithms=[JWT_ALGORITHM],
30 audience=JWT_AUDIENCE,
31 options={"require": ["exp", "sub"]},
32 )
33 except jwt.ExpiredSignatureError:
34 raise HTTPException(
35 status_code=status.HTTP_401_UNAUTHORIZED,
36 detail="Token has expired",
37 headers={"WWW-Authenticate": "Bearer"},
38 )
39 except jwt.InvalidTokenError:
40 raise HTTPException(
41 status_code=status.HTTP_401_UNAUTHORIZED,
42 detail="Could not validate credentials",
43 headers={"WWW-Authenticate": "Bearer"},
44 )
45 
46 return CurrentUser(
47 id=payload["sub"],
48 email=payload.get("email", ""),
49 scopes=payload.get("scopes", []),
50 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Modeling auth as a dependency lets any route request the current user by declaring a single parameter.
  2. 2Verifying signature, algorithm, audience, and required claims together closes off common JWT forgery vectors.
  3. 3Translating decode failures into 401s with a WWW-Authenticate header keeps the API's auth contract explicit.

Related explainers

Share this explainer

Here's the card — post it anywhere.

JWT bearer auth as a FastAPI dependency — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code