Share

Verify a Supabase token in FastAPI as a dependency

Open · 7 views · asked by olu_backend · edited

For a Python backend sitting next to a Supabase frontend. This uses the legacy shared JWT secret from your project settings; if your project issues asymmetric keys, fetch the JWKS instead and keep the rest. Expiry is checked for you.

Snippet
Copied 11 times
# auth.py
import os
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

bearer = HTTPBearer()
SECRET = os.environ["SUPABASE_JWT_SECRET"]


def current_user_id(cred: HTTPAuthorizationCredentials = Depends(bearer)) -> str:
    try:
        claims = jwt.decode(
            cred.credentials,
            SECRET,
            algorithms=["HS256"],
            audience="authenticated",
        )
    except jwt.PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid token")
    return claims["sub"]


# @app.get("/me")
# def me(user_id: str = Depends(current_user_id)):
#     return {"id": user_id}
Comment

Activity