How to Implement JWT Authentication in FastAPI

Introduction

JWT (JSON Web Tokens) provide a stateless authentication mechanism ideal for REST APIs. FastAPI’s dependency injection system makes it straightforward to implement secure, reusable auth.

Step 1: Install Dependencies

pip install pyjwt python-dotenv fastapi

Step 2: Create Token Utilities

import jwt
from datetime import datetime, timedelta, timezone

SECRET = "your-secret-key"

def create_token(user_id: str) -> str:
    payload = {
        "sub": user_id,
        "exp": datetime.now(timezone.utc) + timedelta(hours=1),
    }
    return jwt.encode(payload, SECRET, algorithm="HS256")

def verify_token(token: str) -> dict:
    return jwt.decode(token, SECRET, algorithms=["HS256"])

Step 3: Add Auth Dependency

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

security = HTTPBearer()

async def get_current_user(creds: HTTPAuthorizationCredentials = Depends(security)):
    try:
        payload = verify_token(creds.credentials)
        return payload["sub"]
    except jwt.PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

Step 4: Protect Routes

@app.get("/profile")
async def profile(user_id: str = Depends(get_current_user)):
    return {"user": user_id}

Conclusion

FastAPI’s dependency injection makes JWT auth clean and reusable. The get_current_user dependency can be added to any endpoint that requires authentication.