CognitoJWT

1.4.1 · maintenance · verified Thu Apr 16

CognitoJWT is a Python library designed to decode and verify Amazon Cognito JWT (JSON Web Token) tokens. It simplifies the process of validating ID and Access tokens issued by AWS Cognito User Pools, ensuring their integrity and authenticity. The library supports both synchronous (using `requests`) and asynchronous (using `aiohttp`) modes. While the last release was in 2021 (v1.4.1), its GitHub repository is archived, indicating a maintenance-only status with no active feature development. [2, 14]

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to decode and verify a Cognito JWT token using the synchronous `cognitojwt.decode` function. It requires your AWS region, Cognito User Pool ID, and optionally your App Client ID for `aud` (audience) claim verification. For asynchronous operations, use `cognitojwt.decode_async` within an `async` context. Remember to replace placeholder values with your actual Cognito token and configuration. For production, never set `testmode=True` and ensure tokens are retrieved from a secure authentication flow. [14]

import cognitojwt
import os

# Replace with your actual Cognito details or load from environment variables
id_token = os.environ.get('COGNITO_ID_TOKEN', 'YOUR_COGNITO_ID_TOKEN_HERE') # Example token, should come from authentication flow
region = os.environ.get('AWS_REGION', 'us-east-1')
userpool_id = os.environ.get('COGNITO_USERPOOL_ID', 'us-east-1_XXXXXXXXX')
app_client_id = os.environ.get('COGNITO_APP_CLIENT_ID', 'YOUR_APP_CLIENT_ID') # Optional, but highly recommended for 'aud' claim verification

try:
    # Synchronous mode example
    verified_claims: dict = cognitojwt.decode(
        id_token,
        region,
        userpool_id,
        app_client_id=app_client_id, # Optional: verifies the 'aud' claim matches your app client ID
        testmode=False # Set to True to disable token expiration check for testing only
    )
    print("Token successfully verified (sync mode):")
    print(verified_claims)

    # Asynchronous mode example (requires an async context, e.g., FastAPI, Sanic, or standalone with asyncio.run)
    # import asyncio
    # async def main():
    #     verified_claims_async: dict = await cognitojwt.decode_async(
    #         id_token,
    #         region,
    #         userpool_id,
    #         app_client_id=app_client_id,
    #         testmode=False
    #     )
    #     print("Token successfully verified (async mode):")
    #     print(verified_claims_async)
    # asyncio.run(main())

except cognitojwt.exceptions.CognitoJWTException as e:
    print(f"Token verification failed: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →