Skip to content
FastAPI

JWT Auth

Issue and verify JSON Web Tokens with OAuth2.

#auth#jwt#oauth2

Code

fastapi
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}