JWT Authentication in Python — a practical guide to Python JWT authentication with clear examples you can reuse in real projects.
Python Tutorial Series (81/95). Prefer one article? Read the complete Python tutorial.
Short description
Issue a signed JWT on login and require `Authorization: Bearer <token>` on protected routes.
PyJWT sketch
# pip install PyJWT
import jwt
from datetime import datetime, timedelta, timezone
def create_token(user_id: int, secret: str) -> str:
payload = {
'sub': user_id,
'exp': datetime.now(timezone.utc) + timedelta(hours=24),
}
return jwt.encode(payload, secret, algorithm='HS256')