Backend Boilerplates python Intermediate

FastAPI JWT Auth Dependency

Drop-in FastAPI dependency that validates HS256 Bearer tokens and injects a typed user payload.

python
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt, os

bearer = HTTPBearer()
SECRET = os.environ['JWT_SECRET']

def current_user(creds: HTTPAuthorizationCredentials = Depends(bearer)) -> dict:
    try:
        return jwt.decode(creds.credentials, SECRET, algorithms=['HS256'])
    except jwt.PyJWTError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, 'Invalid token')

Prerequisites

  • fastapi
  • PyJWT

Pro Tips

  • → Store JWT_SECRET in a secrets manager.
  • → Add exp claim to every token.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
4 min
Published
Jun 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.