Create an authentication dependency in auth.py. PyJWKClient downloads and caches HVT's public keys from /.well-known/jwks.json, verifying tokens in ~0.2ms:
python
import os
import jwt
from jwt import PyJWKClient
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
HVT_API_URL = os.getenv("HVT_API_URL", "https://api.hvts.app")
PROJECT_ID = os.getenv("HVT_PROJECT_ID")
# Cache public keys in-memory for 1 hour with automatic kid resolution
jwks_client = PyJWKClient(
f"{HVT_API_URL}/.well-known/jwks.json",
cache_jwk_set=True,
lifespan=3600,
)
asyncdefget_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security)
) -> dict:
token = credentials.credentials
try:
# Resolve the public RSA key matching the token's kid header
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
issuer=HVT_API_URL,
audience=PROJECT_ID,
options={"require": ["exp", "iss", "sub"]},
)
return claims
except jwt.PyJWTError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid or expired token: {str(exc)}",
)
Eliminating Bottlenecks
Unlike implementations that make an HTTP request to /api/v1/auth/runtime/me/ on every request, offline JWKS verification eliminates 50-200ms of latency per call and never overwhelms your auth database.