Registry / aws / cognitojwt

cognitojwt

JSON →
library1.4.1pypypi✓ verified 86d ago

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]

pip install cognitojwt[sync]
INSTALL
IMPORT
SIG · COGNITOJWT
C
cognitojwt
awspythonv1.4.1
Install
4.5s avg
Import
953ms
Disk
47MB
Pass rate
9/ 10
Env Coverage9 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✓ —
✓ 4.81s
py 3.11
✓ —
✓ 4.29s
py 3.12
✓ —
✓ 4.11s
py 3.13
✓ —
✓ 3.56s
py 3.9
4/8 runs
✓ 5.6s
47MB installed
● package 47MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cognitojwt
import cognitojwt

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}")
Debug
Known issues
gotchaThe cognitojwt GitHub repository is archived, meaning it is no longer under active development for new features. While functional, consider this when starting new projects or evaluating long-term maintenance. [2]
fix
Be aware of potential lack of future updates or community support. For new projects, consider alternatives like directly using `python-jose` or more actively maintained AWS SDK integrations if deeper Cognito interaction is needed.
affects: All versions
breakingDo not hardcode Cognito public keys. AWS frequently rotates its signing keys. Always fetch the JSON Web Key Set (JWKS) from the provided Cognito endpoint to ensure signature verification uses the correct, up-to-date keys. [1]
fix
CognitoJWT handles JWKS fetching, but ensure your environment allows outbound network calls to the JWKS endpoint. If deploying in a private VPC without internet access, set the `AWS_COGNITO_JWKS_PATH` environment variable to a local path of the `jwks.json` file. [2, 14]
affects: All versions
gotchaEnsure proper validation of the `token_use` claim. Cognito issues both ID tokens (for user identity) and Access tokens (for API authorization), and mixing them up can lead to security vulnerabilities or validation failures. [1, 4]
fix
After decoding, explicitly check the `token_use` claim in the `verified_claims` dictionary to ensure it matches the expected token type (e.g., 'id' for ID tokens, 'access' for Access tokens) for your application's context. The `app_client_id` parameter can also help verify the `aud` claim.
affects: All versions
gotchaBe mindful of clock skew between your server and the Cognito service. A slight time difference can cause valid tokens to fail expiration checks. [1]
fix
Most JWT libraries, including those underlying cognitojwt, support a small clock tolerance (e.g., 5 minutes) when validating expiration. Ensure this is configured or understood in your environment. The `testmode=True` option in `cognitojwt.decode` should *only* be used for development and *never* in production. [14]
affects: All versions
Errors
Common errors & fixes
Token verification failed: Token is expired
The JWT token's 'exp' (expiration) claim indicates it has passed its valid timestamp.
fix
This is expected behavior for expired tokens. Your application should handle this by prompting the user for re-authentication or using a valid refresh token to obtain new ID and access tokens if applicable. Ensure your system clock is synchronized.
Token verification failed: Invalid signature
The token's signature cannot be verified using the public keys obtained from the Cognito JWKS endpoint, likely due to stale or incorrect JWKS keys, or a tampered token.
fix
Ensure your application can successfully fetch the latest JWKS file from `https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json`. If caching JWKS, clear the cache and re-fetch. Verify that the `region` and `userpool_id` provided to `cognitojwt.decode` are correct. [4]
Token verification failed: Invalid 'aud' claim
The 'aud' (audience) claim in the token's payload does not match the `app_client_id` provided during verification.
fix
Ensure the `app_client_id` passed to `cognitojwt.decode` or `cognitojwt.decode_async` is the correct client ID that the token was issued for. If your application supports multiple client IDs, pass a list or tuple of allowed client IDs. [14]
Token verification failed: Invalid 'iss' claim
The 'iss' (issuer) claim in the token's payload does not match the expected Cognito User Pool issuer URL.
fix
Verify that the `region` and `userpool_id` passed to `cognitojwt.decode` or `cognitojwt.decode_async` correctly correspond to the Cognito User Pool that issued the token. The expected issuer format is `https://cognito-idp.{region}.amazonaws.com/{userPoolId}`. [1]
Upgrade
Version history
1.4.1latest on PyPI · released Jun 7, 2021
Audit
Dependencies
requestsoptionalRequired for synchronous operations if installed with the `[sync]` extra.
aiohttpoptionalRequired for asynchronous operations if installed with the `[async]` extra.
Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources
cognitojwt — pip install cognitojwt · libregistry