Skip to main content

A utility for verifying JWTs issued by AWS Cognito.

Project description

cognito-jwt-verifier

A utility for verifying JWTs issued by AWS Cognito.

✨ Features

  • Async & non‑blocking verification using aiohttp.
  • Automatic JWKS caching & key rollover.
  • Validates both ID and access tokens out‑of‑the‑box.
  • Zero heavy dependencies (only aiohttp, PyJWT, cryptography).

📦 Installation

pip install cognito-jwt-verifier

🚀 Quick Start

import asyncio
from cognito_jwt_verifier import AsyncCognitoJwtVerifier

async def main():
    verifier = AsyncCognitoJwtVerifier(
        issuer="https://cognito-idp.us-east-2.amazonaws.com/<USER_POOL_ID>",
        client_ids=["<APP_CLIENT_ID>"],
    )

    await verifier.init_keys()  # optional warm‑up

    claims = await verifier.verify_id_token("<ID_TOKEN>")
    print(claims)

asyncio.run(main())

🛡️ FastAPI example

from contextlib import asynccontextmanager

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer
from jwt import PyJWTError

from cognito_jwt_verifier import AsyncCognitoJwtVerifier

ISSUER = "https://cognito-idp.us-east-2.amazonaws.com/us-east-2_ae7uogn5r"
CLIENT_IDS = ["4pvqqexampleclientid"]

verifier = AsyncCognitoJwtVerifier(ISSUER, client_ids=CLIENT_IDS)

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl=f"{ISSUER}/oauth2/authorize",
    tokenUrl=f"{ISSUER}/oauth2/token",
)

@asynccontextmanager
async def lifespan(app: FastAPI):
    await verifier.init_keys()
    try:
        yield
    finally:
        await verifier.close()

app = FastAPI(lifespan=lifespan)

async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        return await verifier.verify_access_token(token)
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(exc),
            headers={"WWW-Authenticate": "Bearer"},
        )

@app.get("/user")
async def read_user(user: dict = Depends(get_current_user)):
    return {"user": user}

📚 API at a glance

Method Description
init_keys() Prefetch JWKS (optional).
verify_id_token(token: str) Validate an ID token & return claims.
verify_access_token(token: str) Validate an access token & return claims.
close() Close the internal aiohttp session.

If Cognito rotates its keys, the verifier fetches the new JWKS automatically.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cognito_jwt_verifier-0.0.4.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cognito_jwt_verifier-0.0.4-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file cognito_jwt_verifier-0.0.4.tar.gz.

File metadata

  • Download URL: cognito_jwt_verifier-0.0.4.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for cognito_jwt_verifier-0.0.4.tar.gz
Algorithm Hash digest
SHA256 388e996dd45a3ca3f39c0098703e48518c9807aae05a03ec31a38ddb90f62857
MD5 62c9c0fb0599344d4073dbe60dbc4a34
BLAKE2b-256 598701439f09dcda532b52d7f457d5ae255d3834d7e416fb12dd167e68c8b5ec

See more details on using hashes here.

File details

Details for the file cognito_jwt_verifier-0.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for cognito_jwt_verifier-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 bc1e165f9ee229f143f72768a95e0435179bfa2cc14c67cd45e9c3f56aee5587
MD5 65e33655faafbce1d5f10fd6651eb74b
BLAKE2b-256 5dc2bf40876d07ec93c6cecf59c6fe483906917dc1ca78fffb5612a3f1b8be89

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page