Skip to content
FastAPI

JWT Auth

Issue and verify JSON Web Tokens with OAuth2.

By EZ4Code Team
authjwtoauth2

Code

from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt

SECRET = "change-me"
ALGO = "HS256"
oauth2 = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()

def create_token(data: dict, expires_min: int = 60):
    payload = data.copy()
    payload["exp"] = datetime.now(timezone.utc) + timedelta(minutes=expires_min)
    return jwt.encode(payload, SECRET, algorithm=ALGO)

def current_user(token: str = Depends(oauth2)):
    try:
        return jwt.decode(token, SECRET, algorithms=[ALGO])
    except jwt.PyJWTError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="invalid token")

@app.get("/me")
def me(user=Depends(current_user)):
    return {"user": user}

Explanation

OAuth2PasswordBearer declares a token dependency that the docs surface as an Authorize button. Tokens carry claims and an exp timestamp so they expire automatically. A dependency decodes and verifies the token, raising 401 on failure so any protected route simply declares the dependency.

More FastAPI Snippets