Skip to content

Instantly share code, notes, and snippets.

@daaniam
Created December 19, 2024 06:04
Show Gist options
  • Save daaniam/88a93044032f33a69981755947ba424d to your computer and use it in GitHub Desktop.
Save daaniam/88a93044032f33a69981755947ba424d to your computer and use it in GitHub Desktop.
jwks_firebase

Verify Firebase JWT token with 3rd party (PyJWT)

import logging
from typing import Annotated, Any

from fastapi import Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jwt import PyJWKClient
import jwt


logger = logging.getLogger(__name__)

auth_scheme = HTTPBearer()


def validate_jwt(bearer_payload: Annotated[HTTPAuthorizationCredentials, Depends(auth_scheme)]) -> dict:
    """Decode JTW token and return it as a dictionary."""

    token = bearer_payload.credentials

    google_project_id = "<PROJECT-ID>"

    url = "https://www.googleapis.com/service_accounts/v1/jwk/[email protected]"
    aud = google_project_id
    iss = f"https://securetoken.google.com/{google_project_id}"

    try:
        jwks_client = PyJWKClient(url)
        signing_key = jwks_client.get_signing_key_from_jwt(token).key

        # Decode and verify the token with signing key
        decoded_token = jwt.decode(token, signing_key, algorithms=["RS256"], audience=aud, issuer=iss)

    except jwt.exceptions.InvalidTokenError as err:
        logger.error(f"Invalid token: {err}")
        raise ValueError(err)  # TODO replace with exc

    return decoded_token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment