• v1.7.0
  • Python 3.8 – 3.14
  • MIT

Verify Amazon Cognito JWTs in Python

Check the signature and claims of Cognito ID and access tokens, with a sync API on requests and an async one on aiohttp. One required dependency.

pip install "cognitojwt[sync]"
Complete checksRS256 signature, exp, iat, iss, token_use, aud / client_id.
Key rotation handledCached JWKS, refreshed on unknown keys and every 6 hours, stale-if-error.
Clear errorsTyped exceptions separate an invalid token (401) from unavailable keys (503).
Sync and asyncSame API for both; concurrent calls share one JWKS download.

Installation

The HTTP client is an optional extra, so only what you use gets installed:

pip install "cognitojwt[sync]"     # cognitojwt.decode (requests)
pip install "cognitojwt[async]"    # cognitojwt.decode_async (aiohttp)
pip install "cognitojwt[sync,async]"

Quick start

import cognitojwt

REGION = 'eu-west-1'
USERPOOL_ID = 'eu-west-1_AbC123dEf'
APP_CLIENT_ID = '1example23456789'

# Sync
claims: dict = cognitojwt.decode(token, REGION, USERPOOL_ID, app_client_id=APP_CLIENT_ID)

# Async
claims: dict = await cognitojwt.decode_async(token, REGION, USERPOOL_ID, app_client_id=APP_CLIENT_ID)

The result is a dict with the token claims. Any failure raises a subclass of cognitojwt.CognitoJWTException.

Optional arguments

ArgumentEffect
app_client_idThe app client id, or a list / tuple of ids. Checked against aud (ID token) or client_id (access token).
token_use'id', 'access', or both as a tuple: accept only that kind of token.
leewaySeconds of tolerated clock skew for exp and iat.
testmodeSkip the exp and iat checks. Tests only.

Verifier

CognitoJWTVerifier keeps the configuration of one user pool and its own key cache. Create it once, at start-up, and reuse it.

verifier = cognitojwt.CognitoJWTVerifier(
    REGION,
    USERPOOL_ID,
    APP_CLIENT_ID,
    token_use='access',   # optional
    leeway=30,            # optional
    jwks_url=None,        # optional: URL or file path, e.g. of a local emulator
    issuer=None,          # optional: expected "iss" when jwks_url is set
    timeout=None,         # optional: JWKS download timeout, seconds (default 10)
)

claims = verifier.verify(token)               # needs the "sync" extra
claims = await verifier.verify_async(token)   # needs the "async" extra

Each verifier can point to its own JWKS, so several user pools work side by side in one process.

Errors

Every exception is a subclass of CognitoJWTException, so catching the base class still catches everything.

ExceptionRaised whenAnswer
MalformedTokenErrorNot a JWT, too large (over 128 KiB), invalid JSON, no kid401
InvalidSignatureErrorSignature mismatch, algorithm other than RS256, key not in the JWKS401
TokenExpiredErrorexp has passed401
InvalidClaimErrorWrong or missing exp, iat, iss, token_use, aud / client_id401
InvalidUserPoolErrorregion or userpool_id is not a valid AWS value401 / 500
JWKSErrorThe JWKS can't be downloaded, read or parsed503
try:
    claims = verifier.verify(token)
except cognitojwt.JWKSError:
    ...  # keys unavailable: 503, retry later
except cognitojwt.CognitoJWTException:
    ...  # invalid token: 401

Catch JWKSError before CognitoJWTException, otherwise its branch never runs.

What is verified

  1. The token is parsed and its kid header is read.
  2. The key with that kid is taken from the user pool JWKS, https://cognito-idp.<region>.amazonaws.com/<userpool_id>/.well-known/jwks.json.
  3. The RS256 signature is verified. No other algorithm is accepted.
  4. exp must be in the future (minus leeway).
  5. iat, if present, must not be more than 5 minutes (plus leeway) in the future.
  6. iss must be the user pool.
  7. token_use must match, when passed.
  8. aud or client_id must match app_client_id, when passed.

Not verified: scope, cognito:groups and token revocation. Check scopes and groups in your code after verification.

JWKS cache

  • The JWKS is downloaded once per user pool and cached in memory. Concurrent calls, threads or coroutines, share one download.
  • A token signed with an unknown key (key rotation) triggers a new download, at most once a minute.
  • The JWKS is downloaded again after 6 hours, so keys removed from the pool stop being trusted.
  • If that download fails, the cached keys are still used, a warning goes to the cognitojwt logger, and the download is retried a minute later.
  • A 4xx answer, e.g. for a pool that doesn't exist, is remembered for a minute.
  • Up to 256 pools are cached; the least recently used is dropped first.
from cognitojwt import jwt_sync

jwt_sync.get_keys.cache_info()    # CacheInfo(hits=..., misses=..., maxsize=256, currsize=...)
jwt_sync.get_keys.cache_clear()

The limits live in cognitojwt.constants and can be changed at runtime.

Custom JWKS

In a VPC without internet access, or with a local Cognito emulator, set AWS_COGNITO_JWKS_PATH to a jwks.json file path or URL. Then region and userpool_id are not validated and iss is not checked. A plain http:// URL other than localhost emits a warning.

To set a JWKS for one pool only, pass jwks_url, and optionally issuer, to CognitoJWTVerifier.

Security notes

  • Always pass app_client_id. Without it, a token issued for any app client of the pool is accepted.
  • Never take the region or user pool id from the token you are verifying. With several pools, look them up in your own list.
  • Pass token_use when an endpoint expects only access or only ID tokens.
  • Never use testmode=True in production.

Examples

FastAPI dependency

import cognitojwt
from fastapi import Depends, FastAPI, HTTPException, Request

verifier = cognitojwt.CognitoJWTVerifier(REGION, USERPOOL_ID, APP_CLIENT_ID, token_use='access')
app = FastAPI()


async def current_user(request: Request) -> dict:
    scheme, _, token = request.headers.get('Authorization', '').partition(' ')
    if scheme.lower() != 'bearer' or not token:
        raise HTTPException(401, 'Missing bearer token')
    try:
        return await verifier.verify_async(token)
    except cognitojwt.JWKSError:
        raise HTTPException(503, 'Authentication is temporarily unavailable')
    except cognitojwt.CognitoJWTException:
        raise HTTPException(401, 'Invalid token')


@app.get('/me')
async def me(user: dict = Depends(current_user)) -> dict:
    return {'sub': user['sub']}

Several user pools

VERIFIERS = {
    'tenant-a': cognitojwt.CognitoJWTVerifier('eu-west-1', 'eu-west-1_AAAAAAAAA', 'client-a'),
    'tenant-b': cognitojwt.CognitoJWTVerifier('us-east-1', 'us-east-1_BBBBBBBBB', 'client-b'),
}

def verify_for_tenant(tenant: str, token: str) -> dict:
    verifier = VERIFIERS.get(tenant)
    if verifier is None:
        raise PermissionError('Unknown tenant')
    return verifier.verify(token)

Scopes and groups

claims = verifier.verify(token)
if 'orders/read' not in claims.get('scope', '').split():
    raise PermissionError('Missing scope')
if 'admin' not in claims.get('cognito:groups', []):
    raise PermissionError('Not an admin')

For LLMs

Machine-readable docs following the llms.txt convention: