PyJWT Key Fetcher

0.8.0 · active · verified Thu Apr 16

PyJWT Key Fetcher is an async Python library designed to fetch JSON Web Key Sets (JWKS) for JWT token verification. It automatically retrieves issuer configurations (e.g., from OpenID Connect discovery endpoints) to locate JWKS URIs and fetch the correct public keys. This library acts as an improved async replacement for `PyJWKClient` from PyJWT. The current version is 0.8.0, and it maintains a relatively active release cadence with several updates per year.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `AsyncKeyFetcher` to retrieve a signing key from a JWT's issuer, and then use that key with `PyJWT` to decode and verify the token. It includes `valid_issuers` for security and explicitly passes `audience` and `issuer` to `jwt.decode` for full validation.

import asyncio
import jwt
from pyjwt_key_fetcher import AsyncKeyFetcher

async def main():
    # Example token from PyJWT documentation for demonstration
    # In a real app, this would come from an Authorization header
    token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5FRTFRVVJCT1RNNE16STVSa0ZETlRZeE9UVTFNRGcyT0Rnd1EwVXpNVGsxUWpZeVJrUkZRdyJ9.eyJpc3MiOiJodHRwczovL2Rldi04N2V2eDlydS5hdXRoMC5jb20vIiwic3ViIjoiYVc0Q2NhNzl4UmVMV1V6MGFFMkg2a0QwTzNjWEJWdENAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vZXhwZW5zZXMtYXBpIiwiaWF0IjoxNTcyMDA2OTU0LCJleHAiOjE1NzIwMDY5NjQsImF6cCI6ImFXNENjYTc5eFJlTFdVejBhRTJINmtEME8zY1hCVnRDIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.PUxE7xn52aTCohGiWoSdMBZGiYAHwE5FYie0Y1qUT68IHSTXwXVd6hn02HTah6epvHHVKA2FqcFZ4GGv5VTHEvYpeggiiZMgbxFrmTEY0csL6VNkX1eaJGcuehwQCRBKRLL3zKmA5IKGy5GeUnIbpPHLHDxr-GXvgFzsdsyWlVQvPX2xjeaQ217r2PtxDeqjlf66UYl6oY6AqNS8DH3iryCvIfCcybRZkc_hdy-6ZMoKT6Piijvk_aXdm7-QQqKJFHLuEqrVSOuBqqiNfVrG27QzAPuPOxvfXTVLXL2jek5meH6n-VWgrBdoMFH93QEszEDowDAEhQPHVs0xj7SIzA"

    fetcher = AsyncKeyFetcher(valid_issuers=["https://dev-87evx9ru.auth0.com/"])
    try:
        key_entry = await fetcher.get_key(token)
        # The fetched key_entry can then be used with PyJWT's decode function
        decoded_token = jwt.decode(
            jwt=token,
            options={"verify_exp": False}, # Set to True for production
            audience="https://expenses-api",
            issuer="https://dev-87evx9ru.auth0.com/",
            **key_entry
        )
        print("Successfully decoded token:", decoded_token)
    except Exception as e:
        print(f"Error decoding token: {e}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →