- 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]"
exp, iat, iss, token_use, aud / client_id.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
| Argument | Effect |
|---|---|
app_client_id | The 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. |
leeway | Seconds of tolerated clock skew for exp and iat. |
testmode | Skip 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" extraEach 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.
| Exception | Raised when | Answer |
|---|---|---|
MalformedTokenError | Not a JWT, too large (over 128 KiB), invalid JSON, no kid | 401 |
InvalidSignatureError | Signature mismatch, algorithm other than RS256, key not in the JWKS | 401 |
TokenExpiredError | exp has passed | 401 |
InvalidClaimError | Wrong or missing exp, iat, iss, token_use, aud / client_id | 401 |
InvalidUserPoolError | region or userpool_id is not a valid AWS value | 401 / 500 |
JWKSError | The JWKS can't be downloaded, read or parsed | 503 |
try:
claims = verifier.verify(token)
except cognitojwt.JWKSError:
... # keys unavailable: 503, retry later
except cognitojwt.CognitoJWTException:
... # invalid token: 401Catch JWKSError before CognitoJWTException, otherwise its branch never runs.
What is verified
- The token is parsed and its
kidheader is read. - The key with that
kidis taken from the user pool JWKS,https://cognito-idp.<region>.amazonaws.com/<userpool_id>/.well-known/jwks.json. - The RS256 signature is verified. No other algorithm is accepted.
expmust be in the future (minusleeway).iat, if present, must not be more than 5 minutes (plusleeway) in the future.issmust be the user pool.token_usemust match, when passed.audorclient_idmust matchapp_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
cognitojwtlogger, 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_usewhen an endpoint expects only access or only ID tokens. - Never use
testmode=Truein 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: