Authentication and SecurityLesson 4.2
How to create and verify JWT tokens in FastAPI
JWT structure, python-jose, SECRET_KEY, algorithm HS256, token expiry, create_access_token, decode token, JWTError handling, payload claims
Creating and Verifying JWT Tokens
A JWT (JSON Web Token) is a signed string carrying claims like user ID and expiry. FastAPI uses python-jose to create and verify them.
Install
pip install python-jose[cryptography]Token creation and verification
from datetime import datetime, timedelta
from jose import JWTError, jwt
SECRET_KEY = "your-secret-key-change-this"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def create_access_token(data: dict) -> str:
payload = data.copy()
expire = datetime.utcnow() + timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
payload["exp"] = expire
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def decode_token(token: str) -> dict:
try:
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(
status_code=401,
detail="Invalid or expired token"
)
The exp claim is checked automatically during jwt.decode. An expired token raises JWTError. Store the SECRET_KEY in an environment variable — never hardcode it in source.
Use HS256 for single-server deployments. For multi-service architectures where you need to verify tokens without sharing the secret, switch to RS256 (asymmetric).
