Verify a Cognito JWT (Access Token or ID Token) in Node.js and Python: aws-jwt-verify, PyJWT, the aud vs client_id Trap, and Every Error Message
To verify a Cognito JWT, check its RS256 signature against your user pool's public keys at https://cognito-idp.REGION.amazonaws.com/USER_POOL_ID/.well-known/jwks.json (matched by the token's kid). Then confirm the claims: iss is your user pool, token_use is access or id as you expect, the token is for your app client, and exp is in the future. In Node.js the recommended library is aws-jwt-verify: CognitoJwtVerifier.create({ userPoolId, tokenUse: "access", clientId }), then await verifier.verify(token). In Python, PyJWT with PyJWKClient does the signature work. Here is the trap behind most failed verifications: Cognito access tokens have no aud claim. The app client is in client_id instead, and an aud appears only if you requested a resource binding. So PyJWT called with audience=CLIENT_ID rejects every valid access token with "Token is missing the "aud" claim". Called without an audience, it rejects every valid ID token with "Invalid audience", because ID tokens do carry aud. This page covers both tokens, working code for Node.js, Python, Lambda and API Gateway, and the exact error message for every way verification can fail, from "Token use not allowed: id. Expected: access" to "Invalid signature".
Jake's shop added online booking, with customers signing in through Cognito and a small Python API behind it. The first test came back 401 on every single request. Ethan's code was checking the audience, the way every JWT tutorial shows. "So the login works and the API refuses it?" Jake asked. "The login hands out a token without the field my code demands," Ethan said, after decoding one. "The client ID is in there. It's just under a different name."
New to Cognito? Amazon Cognito user pools handle sign-up and sign-in for your app. When a user signs in, Cognito returns three tokens: an ID token (who the user is), an access token (what they may call), and a refresh token (to get new ones). The first two are JSON Web Tokens (JWTs): three base64url-encoded parts separated by dots (header, payload and signature). Anyone can read a JWT, because the payload is only encoded, not encrypted. What makes it trustworthy is the signature, which only Cognito's private key can produce. "Verifying" a JWT means checking that signature and a handful of claims before your backend believes a word of it.
What is inside a Cognito access token and ID token
| Claim | Access token | ID token | What to check |
|---|---|---|---|
iss | Your user pool URL | Your user pool URL | Equals https://cognito-idp.REGION.amazonaws.com/POOL_ID |
token_use | access | id | The type you expect |
client_id | Your app client ID | Not present | Access tokens: your client ID |
aud | Only with resource binding (an API URL) | Your app client ID | ID tokens: your client ID |
exp, iat, auth_time | Yes | Yes | exp in the future |
sub | User's unique ID | User's unique ID | Use as your user key |
scope | Space-separated OAuth scopes | Not present | Required scopes for the route |
username / cognito:username | username | cognito:username, plus attributes such as email | Display only; key on sub |
cognito:groups | If the user is in groups | If the user is in groups | Role-based access |
The header of both tokens holds kid (which of the pool's keys signed it) and alg (RS256). A Cognito access token also carries jti and origin_jti identifiers and an event_id, and an ID token carries the user's profile attributes such as email and email_verified. Note the different names for the same idea: the access token's username is the ID token's cognito:username, and the access token's client_id is the ID token's aud.
Access token or ID token: which one should your API accept?
For calling your API, accept the access token. It is designed for authorization: it carries scopes and groups, it says which app client asked for it, and its token_use is access. The ID token is for the client app itself, to show the user's name and email without another call. Many apps send the ID token to their API because it "has the email in it". That works if you verify it properly, but it mixes up two jobs and loses scope-based authorization. If your API needs the user's email, look it up by sub, or include it with a pre-token-generation trigger. Our API Gateway Cognito authorizer guide shows how the same choice plays out in API Gateway.
The six checks every Cognito JWT verifier must do
- Parse the token into header, payload and signature. Reject anything that is not exactly three dot-separated parts.
- Find the signing key. Read
kidfrom the header, and fetch the matching public key from your pool's JWKS URL. Reject tokens whosekidis not in the set. - Check the signature with RS256 using that key. Accept only RS256, never
noneor HMAC algorithms. - Check the issuer:
issmust equalhttps://cognito-idp.REGION.amazonaws.com/POOL_ID, exactly. - Check the token type and app client:
token_usemust be the type you expect. For access tokens,client_idmust be one of your app clients. For ID tokens,audmust be. - Check the time:
expmust be in the future (allow a few seconds of clock skew at most). Then checkscopeorcognito:groupsif the route needs them.
Skipping any one of these opens a real hole. Without the issuer check, a token from any Cognito pool, including one an attacker creates, passes. Without the client check, tokens issued to your other apps work here too. And without token_use, an ID token can stand in for an access token. "Six checks for one login," Jake said. "Six locks on one door," Ethan said. "A library turns all six for you."
Verify a Cognito token in Node.js with aws-jwt-verify
aws-jwt-verify is AWS's own library for this job. Install it with npm install aws-jwt-verify (version 5.2.1 in October 2026). It fetches and caches the JWKS and runs all six checks:
const { CognitoJwtVerifier } = require("aws-jwt-verify");
// Create once, outside your request handler, so the JWKS cache is reused
const verifier = CognitoJwtVerifier.create({
userPoolId: "us-east-1_ExaMPle1",
tokenUse: "access", // or "id"
clientId: "1example23456789", // or an array of client IDs
});
async function authenticate(req, res, next) {
const token = (req.headers.authorization || "").replace(/^Bearer /, "");
try {
const claims = await verifier.verify(token);
req.user = { sub: claims.sub, username: claims.username, groups: claims["cognito:groups"] || [] };
next();
} catch (err) {
console.warn("JWT rejected:", err.name, err.message);
res.status(401).json({ message: "Unauthorized" });
}
}
Useful options:
tokenUse: nullaccepts both token types, which is rarely what you want. Name the one you expect.clientId: ["app1", "app2"]accepts several app clients. Usenullonly if you deliberately accept any client of this pool.scope: "shop/admin"requires a scope in an access token. You can also pass an array of acceptable scopes.groups: "admins"requires membership of a Cognito group. A user in another group fails with "Cognito group not allowed: staff. Expected: admins", and a user in no group with "Missing Cognito group. Expected: admins".await verifier.hydrate()at startup downloads the JWKS before the first request, so the first user does not pay the fetch time.
For several user pools, pass an array of configurations to CognitoJwtVerifier.create([...]). The verifier picks the right one by the token's issuer. Map errors to a plain 401 for the caller, and log the real reason on the server only, so attackers learn nothing from your responses.
How fast is verification? (Fast enough to do on every request)
With the JWKS cached, verifying a token is pure CPU work: one RSA signature check and a few comparisons. On an ordinary laptop CPU, aws-jwt-verify checked 5,000 Cognito-style access tokens in about half a second, roughly 0.1 milliseconds per token. That is far below the cost of a database query or a network hop, so verify on every request and skip caching the results. Caching "this token was valid" only adds a way to keep accepting a token after it expires. The expensive part is the first JWKS download, which is a network call, and that is why you create the verifier once and, ideally, hydrate it at startup.
Per-route rules: groups and scopes in Express
Most APIs have a few routes that need more than "signed in". Verify once in middleware, then check claims per route:
const requireGroup = (group) => (req, res, next) =>
(req.user.groups || []).includes(group) ? next() : res.status(403).json({ message: "Forbidden" });
const requireScope = (scope) => (req, res, next) =>
(req.claims.scope || "").split(" ").includes(scope) ? next() : res.status(403).json({ message: "Forbidden" });
app.get("/bookings", authenticate, listBookings); // any signed-in user
app.delete("/bookings/:id", authenticate, requireGroup("admins"), cancel); // staff only
app.get("/reports", authenticate, requireScope("shop/reports.read"), report);// machine clients
Use 401 when the token is missing or invalid, and 403 when it is valid but not allowed. That difference tells the client whether to sign in again or give up. In authenticate, store the verified claims on req.claims as well as the friendlier req.user. The alternative, separate verifiers with groups or scope options per route, works too, and it is the better fit when an entire service is admin-only.
A checklist before you ship
- The verifier is created once, outside request handlers, and hydrated at startup if possible.
- Issuer, token type and app client are all checked:
client_idfor access tokens,audfor ID tokens. - Only RS256 is accepted.
- Routes that need more than sign-in check groups or scopes, with 403 for "valid but not allowed".
- Errors return a plain 401, and logs record the reason and
sub, never the token. - Access tokens are short-lived, and high-risk actions use a live Cognito check or your own revocation list.
- The backend can reach the JWKS URL, or has the keys loaded at deploy time.
- You have tested the failure cases: an ID token, an expired token, a token from another client, and a tampered token.
Front-end mistakes that break verification
Many "my verifier rejects valid tokens" reports turn out to be the client sending the wrong thing. Check these on the front end before you change backend code:
- Sending the ID token. Front-end SDKs return both tokens from the user's session, and the ID token is often the one an example happens to print. Send the access token to your API.
- A malformed header. The header should be exactly
Authorization: Bearer eyJ.... Extra quotes, a missing space, or the word "Bearer" twice all turn into parse errors on the server. - Sending a stale token. If the app caches the token at sign-in and never refreshes it, every call fails after an hour. Read the current token from the SDK's session before each call, and let the SDK refresh it.
- Tokens in the URL. Query strings end up in server logs, browser history and analytics. Send tokens in the header.
- Where the token lives. Tokens in
localStorageare readable by any script on the page, so a cross-site scripting bug leaks them. Many teams keep tokens in memory, or in secure, HttpOnly cookies set by a backend. Cookie-based setups need CSRF protection instead. Either way, the server-side verification on this page stays the same.
Every aws-jwt-verify error, with its exact message
These are the errors aws-jwt-verify 5.2.1 throws, produced by signing Cognito-shaped tokens with a test key and verifying them against a verifier for pool us-east-1_ExaMPle1 and client 1example23456789:
| Situation | Error class | Message |
|---|---|---|
| ID token sent to an access-token verifier | CognitoJwtInvalidTokenUseError | Token use not allowed: id. Expected: access |
| Token from a different app client | CognitoJwtInvalidClientIdError | Client ID not allowed: 1example23456789. Expected: otherclient999 |
| Expired token | JwtExpiredError | Token expired at 2026-10-22T20:40:56.000Z |
| Token from another user pool | ParameterValidationError | issuer not configured: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_OtherPool |
| Payload edited after signing | JwtInvalidSignatureError | Invalid signature |
| Required scope missing | JwtInvalidScopeError | Scope not allowed: openid, email. Expected: shop/admin |
| Not a JWT (for example "Bearer abc.def") | JwtParseError | JWT string does not consist of exactly 3 parts (header, payload, signature) |
Two of these deserve a note. The client ID message shows the token's client first and the one you configured second, so "Client ID not allowed: X. Expected: Y" means the token came from app client X. Check which client your front end uses. And the "Not a JWT" error often comes from passing the whole Authorization header, including Bearer , or a header with quotes around the token. Strip both before verifying.
Verify a Cognito token in Python with PyJWT
Python has no AWS-published equivalent, but PyJWT (2.15.1 in October 2026, installed with pip install "pyjwt[crypto]") handles keys and signatures. The Cognito-specific checks are yours to add:
import jwt
REGION, POOL_ID, CLIENT_ID = "us-east-1", "us-east-1_ExaMPle1", "1example23456789"
ISSUER = f"https://cognito-idp.{REGION}.amazonaws.com/{POOL_ID}"
jwks_client = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json") # create once; it caches keys
def verify_access_token(token: str) -> dict:
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(token, signing_key.key, algorithms=["RS256"], issuer=ISSUER)
if claims.get("token_use") != "access":
raise jwt.InvalidTokenError(f"token_use is {claims.get('token_use')}, expected access")
if claims.get("client_id") != CLIENT_ID:
raise jwt.InvalidTokenError("token was issued to a different app client")
return claims
def verify_id_token(token: str) -> dict:
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(token, signing_key.key, algorithms=["RS256"], issuer=ISSUER, audience=CLIENT_ID)
if claims.get("token_use") != "id":
raise jwt.InvalidTokenError("expected an ID token")
return claims
Notice the difference between the two functions. Access tokens are decoded without audience=, and client_id is checked by hand. ID tokens are decoded with audience=CLIENT_ID. Getting this backwards produces the two most common Python errors (next section). PyJWT checks exp automatically and raises ExpiredSignatureError. Pass leeway=10 to allow 10 seconds of clock skew between servers.
The aud vs client_id trap, explained
OAuth 2.0 and OpenID Connect use aud (audience) to say who a token is for, and most JWT libraries check it by default when you give them an audience. Cognito follows OpenID Connect for ID tokens, where aud is the app client ID. Cognito access tokens are different: the app client goes in client_id, and aud appears only when your app requested a resource binding, in which case it holds the URL of the API the token is meant for. With PyJWT, that difference gives you these exact results:
# Access token, decoded with audience=CLIENT_ID
MissingRequiredClaimError: Token is missing the "aud" claim
# ID token, decoded with no audience argument
InvalidAudienceError: Invalid audience
# Access token without audience= plus a manual client_id check: OK
# ID token with audience=CLIENT_ID: OK
The second one surprises people most. PyJWT rejects a token that has an aud claim when you do not say which audience you expect. That is a safety feature, because a token meant for someone else should not slip through. Other libraries and frameworks behave similarly, so the fix is the same everywhere: check aud for ID tokens and client_id for access tokens, or use aws-jwt-verify, which knows the difference. "So the client ID was in the token all along," Jake said. "Under a different label," Ethan said, "depending on which token you hold."
Machine-to-machine tokens (client credentials)
When a backend service, not a person, gets a token with the OAuth client credentials grant, the access token looks different, and verifiers written for user tokens trip over it:
subequalsclient_id. In machine-to-machine (M2M) tokens, the subject is the app client that asked, not a user. Code that lookssubup in a users table will fail.- No
username,cognito:groupsororigin_jti. There is no user, so no username or groups, and no refresh token, so nothing to link a revocation to. Code that readsclaims["username"]raises a KeyError on M2M tokens. - Scopes do the authorizing. M2M tokens carry the custom scopes of your resource server (for example
shop/orders.read). Check them, withscopein aws-jwt-verify or a manual check in Python. token_useis stillaccess, andiss,exp,iatandjtiare present, so the six checks apply unchanged.
If one API serves both people and machines, branch on whether sub == client_id, or give the two kinds of callers different scopes, and write the authorization rules against scopes rather than usernames.
Sign-out and revocation: what verification cannot see
A Cognito JWT is self-contained: its signature and expiry are fixed when it is issued. Cognito can revoke tokens with RevokeToken, the revoke endpoint, or GlobalSignOut, and revoking a refresh token invalidates the access tokens it issued for Cognito's own API calls. But revoked tokens still pass any JWT library that checks only the signature and expiry, which is what aws-jwt-verify, PyJWT and API Gateway's JWT authorizer do. In practice:
- Keep access tokens short-lived. A 5 to 60 minute lifetime limits how long a revoked or stolen token works.
- For high-risk actions such as payments, admin changes or password changes, call a Cognito API that requires a live token (for example
GetUser), which fails for revoked tokens. Or keep your own list of revokedjtiororigin_jtivalues. - Revoke the refresh token on sign-out, so the client cannot mint new access tokens. The old access token then dies at its next expiry.
Several app clients or user pools
Real systems often have a web client, a mobile client and an internal admin client, each with its own client ID, and sometimes separate pools for customers and staff. aws-jwt-verify handles both:
// Several app clients of one pool
CognitoJwtVerifier.create({ userPoolId: "us-east-1_Customers", tokenUse: "access",
clientId: ["webclient111", "mobileclient222"] });
// Two pools: the verifier picks the right config from the token's issuer
CognitoJwtVerifier.create([
{ userPoolId: "us-east-1_Customers", tokenUse: "access", clientId: "webclient111" },
{ userPoolId: "us-east-1_Staff", tokenUse: "access", clientId: "adminclient333", groups: "admins" },
]);
In Python, keep one PyJWKClient per pool and a mapping from issuer to allowed client IDs. Decode the issuer without verifying first, using jwt.decode(token, options={"verify_signature": False})["iss"], only to pick the right pool, then verify fully with that pool's keys. A token whose issuer is not in your map is rejected before any key lookup, which matches aws-jwt-verify's "issuer not configured" behavior.
PyJWT error reference for Cognito tokens
| Exception: message | Cause | Fix |
|---|---|---|
MissingRequiredClaimError: Token is missing the "aud" claim | Access token decoded with audience= | Drop audience= and check client_id |
InvalidAudienceError: Invalid audience | ID token decoded without audience=, or the wrong client ID | Pass audience=CLIENT_ID for ID tokens |
ExpiredSignatureError: Signature has expired | exp has passed, or the server clock is wrong | Refresh the token; sync the clock; small leeway |
InvalidIssuerError: Invalid issuer | Token from another pool or Region | Check the pool ID and Region in your issuer |
PyJWKClientError: Unable to find a signing key that matches | kid not in your pool's JWKS | Wrong pool, stale cache, or forged token |
DecodeError: Not enough segments | Not a JWT (for example abc.def), or the header was not stripped | Remove Bearer and quotes before decoding |
All of these inherit from jwt.PyJWTError, so one except jwt.PyJWTError catches every verification failure, as in the FastAPI example. Log the class name and message on the server, and return a plain 401.
JWKS, key IDs and key rotation
Your pool's public keys live at https://cognito-idp.REGION.amazonaws.com/POOL_ID/.well-known/jwks.json, as a JSON Web Key Set: a list of keys, each with a kid, alg (RS256), and the RSA modulus and exponent. The token's kid tells you which key to use. Three practical rules follow:
- Cache the keys, keyed by
kid, instead of fetching them on every request. Both aws-jwt-verify and PyJWT'sPyJWKClientcache for you, as long as you create the verifier or client once, outside the request handler. - Refresh on an unknown
kid, not on a timer. If a token arrives with akidyou have not cached, fetch the set again once, because keys can change over a pool's lifetime and a fixed timer would either refetch needlessly or miss the change. - Reject a
kidthat is still missing after a refresh. PyJWKClient raises "Unable to find a signing key that matches: "rotated-key-9"", and a token with nokidat all gives "Unable to find a signing key that matches: "None"".
The JWKS URL is public and needs no credentials. If your backend runs in a private subnet with no internet route, it cannot reach it, and every first verification will hang or time out. Either give the function a route out (a NAT gateway), or download the JWKS at deploy time and load it into the verifier. aws-jwt-verify's verifier.cacheJwks(jwks) accepts a JWKS you already have.
Get real tokens for testing with the AWS CLI or boto3
To test your verifier, sign in a test user and capture its tokens. The app client must allow the USER_PASSWORD_AUTH flow for this, so enable it on a test client only:
- Create a test user with a permanent password:
aws cognito-idp admin-create-user --user-pool-id POOL_ID --username jake --message-action SUPPRESS, thenaws cognito-idp admin-set-user-password --user-pool-id POOL_ID --username jake --password 'Shop-Pass-2026!' --permanent. - Sign in with
aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --client-id CLIENT_ID --auth-parameters USERNAME=jake,PASSWORD='Shop-Pass-2026!'. The response'sAuthenticationResultholdsAccessToken,IdToken,RefreshToken,ExpiresIn(3,600 for a one-hour token) andTokenType: Bearer. - Pull out just the access token with
--query AuthenticationResult.AccessToken --output textand store it in a shell variable. - Call your API with
curl -H "Authorization: Bearer $TOKEN" https://your-api/..., and decode the token locally if the call fails. - Test the failure cases on purpose: send the ID token where the access token belongs, wait for expiry (or set a 5-minute validity on the test client), and edit one character of the token to see the signature check fail.
In Python, boto3's cognito-idp client does the same with client.initiate_auth(AuthFlow="USER_PASSWORD_AUTH", ClientId=CLIENT_ID, AuthParameters={"USERNAME": "jake", "PASSWORD": "..."}), and the tokens are in response["AuthenticationResult"]. If the app client has a secret, add a SECRET_HASH parameter. If sign-in itself fails, our "Incorrect username or password" guide covers the usual causes. Production apps should use the hosted sign-in pages or SRP-based flows rather than sending passwords this way, so keep USER_PASSWORD_AUTH to test clients.
Refreshing tokens when they expire
When an access token expires, the client asks for new tokens with the refresh token instead of making the user sign in again:
aws cognito-idp initiate-auth --auth-flow REFRESH_TOKEN_AUTH --client-id CLIENT_ID \
--auth-parameters REFRESH_TOKEN=$REFRESH_TOKEN
The response contains a new access token and ID token with fresh exp times, and no new refresh token unless refresh token rotation is on. In boto3 the same call is initiate_auth(AuthFlow="REFRESH_TOKEN_AUTH", ClientId=CLIENT_ID, AuthParameters={"REFRESH_TOKEN": token}). Your backend's verifier needs no change, because the new tokens are signed by the same pool keys. The usual client pattern is to refresh a minute or two before exp, or to retry once with a refreshed token when the API returns 401. When the refresh token itself expires (30 days by default), the user signs in again.
A FastAPI dependency that verifies Cognito access tokens
In Python web frameworks, wrap the verification in a dependency so every protected route gets it for free. Here it is for FastAPI, using verify_access_token from the Python section:
import jwt
from fastapi import FastAPI, Depends, HTTPException, Header
def current_user(authorization: str = Header(default="")) -> dict:
token = authorization.removeprefix("Bearer ").strip()
try:
return verify_access_token(token)
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Unauthorized")
app = FastAPI()
@app.get("/bookings")
def bookings(user: dict = Depends(current_user)):
return {"user": user["username"], "bookings": []}
With a valid access token, /bookings returns 200 and {"user": "jake", "bookings": []}. With an ID token, or no header at all, it returns 401 and {"detail": "Unauthorized"}. The ID token fails because jwt.decode without an audience rejects tokens that carry aud, exactly the safety behavior described in the aud section. In Flask or Django the same function fits in a decorator or middleware. The verification code does not change, only how you call it.
Adding custom claims: the pre token generation trigger
If your API needs data that is not in the token, such as a customer tier or a store ID, a pre token generation Lambda trigger can add, change or remove claims before Cognito signs the tokens. The version you choose decides which tokens you can change:
- Version 1 events customize the ID token only, and they work on any feature plan.
- Version 2 (V2_0) events customize both ID and access tokens for user sign-ins, on user pools with the Essentials or Plus feature plan.
- Version 3 (V3_0) events also cover access tokens issued to machines through the client credentials flow, on the same plans.
Custom claims are signed like the rest of the token, so your verifier trusts them after the normal checks, with no extra step. Keep them small, because every claim travels with every request and very large tokens can hit header size limits on load balancers and proxies. Put identifiers in the token, and look up bulky data on the server.
Other languages and frameworks
The six checks are the same everywhere, so any JWT library with JWKS support can verify Cognito tokens. Point it at your pool's JWKS URL, allow only RS256, set the issuer, and add the token_use and client_id (or aud) checks if the library does not do them itself. Popular choices include the JOSE libraries for Go and Java and the built-in JWT bearer handlers in ASP.NET Core. Most framework handlers validate aud by default, which means they reject Cognito access tokens out of the box, just as PyJWT does, until you switch the audience check to client_id. If you are writing a new Node.js service, aws-jwt-verify saves you from all of this.
Verifying tokens in AWS Lambda
In Lambda, the most important detail is where you create the verifier. Code outside the handler runs once per execution environment and is reused across invocations, so the JWKS is fetched once, not on every call:
// Node.js Lambda (for example a Lambda authorizer)
const { CognitoJwtVerifier } = require("aws-jwt-verify");
const verifier = CognitoJwtVerifier.create({
userPoolId: process.env.USER_POOL_ID, tokenUse: "access", clientId: process.env.CLIENT_ID });
exports.handler = async (event) => {
const token = (event.headers?.authorization || "").replace(/^Bearer /, "");
try {
const claims = await verifier.verify(token);
return { isAuthorized: true, context: { sub: claims.sub } };
} catch {
return { isAuthorized: false };
}
};
That return shape is the "simple response" format for HTTP API Lambda authorizers. For REST API authorizers you return an IAM policy instead. Keep the pool ID and client ID in environment variables rather than in code, and use the same pattern in Python with a module-level PyJWKClient. In many cases you do not need your own code at all, because API Gateway can verify Cognito tokens itself (next section).
Let API Gateway verify the token: the HTTP API JWT authorizer
For HTTP APIs, a built-in JWT authorizer verifies tokens with no code. You configure the issuer (your pool URL) and one or more audiences (your app client IDs), and API Gateway then checks the following:
- the
kidmatches a key at the issuer'sjwks_uri, and the RSA signature is valid; issmatches the configured issuer;audorclient_idmatches one of the configured audiences. API Gateway checksclient_idonly ifaudis absent, so plain Cognito access tokens work, and if both are present it checksaud;expis after the current time, andnbfandiatare before it;- if the route has scopes, the token's
scope(orscp) includes at least one of them.
API Gateway caches the public keys for up to two hours on a best-effort basis, so a newly added key may take a while to be picked up. The JWT authorizer does not check token_use, and an ID token carries aud equal to your client ID too. If you configure only the client ID as an audience, ID tokens are accepted as well. To accept only access tokens, require a scope on the route, since ID tokens have no scope. REST APIs use a different feature, the Cognito user pool authorizer, which our Cognito authorizer 401 guide covers.
Token expiration: how long Cognito tokens last
- Access and ID tokens can be set per app client to anything from 5 minutes to 1 day. The common setting is one hour, which shows in the token as
expminusiat= 3,600 seconds. - Refresh tokens default to 30 days and can be set from 60 minutes to 10 years. With refresh token rotation, each new refresh token is valid only for the time remaining in the original window, so rotating does not extend a session.
- Expired tokens fail verification with
JwtExpiredErrorin aws-jwt-verify orExpiredSignatureError: Signature has expiredin PyJWT. The client should then use the refresh token to get new ones, not ask the user to sign in again. - Revocation: a signed JWT stays valid until it expires, even after the user signs out, unless your app checks revocation. Short access token lifetimes limit the damage of a leaked token.
Clock skew is the hidden cause of "expired" errors on tokens that were just issued. If a server's clock runs fast, a fresh token looks old. Keep servers on NTP (EC2 does this by default with Amazon Time Sync), and allow a few seconds of leeway at most.
Decoding a token to debug it (safely)
When verification fails, look inside the token. The payload is base64url-encoded JSON, so you can read it without any library or website:
python3 -c "import sys,base64,json; _,p,_=sys.argv[1].split('.'); print(json.dumps(json.loads(base64.urlsafe_b64decode(p + '=' * (-len(p) % 4))), indent=2))" "$TOKEN"
Check token_use, iss, client_id or aud, and exp (a Unix timestamp; date -d @1676317451 converts it). Most failures are obvious once you see the claims: the wrong token type, the wrong pool, or an expired token. The header part decodes the same way and shows the kid, which you can compare with the keys listed at your pool's JWKS URL. Decode production tokens locally rather than on a website, because a valid token is a live credential until it expires. And treat what you decoded as a clue, not a fact: decoding proves nothing about who made the token, only verifying does.
Six security mistakes, and the safe habit for each
- Trusting decoded claims without checking the signature. Anyone can forge a payload. Only the signature proves Cognito wrote it.
- Accepting any algorithm. Pass
algorithms=["RS256"]explicitly. Libraries that trusted the token's ownalgheader have been tricked withnoneor HMAC in the past. - Skipping the issuer check. Every Cognito pool in the world signs valid tokens, so check that the token comes from your pool.
- Skipping
token_use, which lets ID tokens act as access tokens. - Logging whole tokens. Log
suband the error, not the token. A logged token can be replayed until it expires. - Returning the real error to the caller. A plain 401 for the caller, with the detail in your server logs, gives attackers nothing to work with.
Troubleshooting by symptom
Every access token fails with Token is missing the aud claim
Your code passes audience= for access tokens. Remove it and check client_id yourself, or use aws-jwt-verify with tokenUse "access".
ID tokens fail with Invalid audience
PyJWT rejects tokens with an aud claim when no audience is given. Pass audience=CLIENT_ID for ID tokens.
Token use not allowed: id. Expected: access
The front end is sending the ID token. Send the access token to the API, or create a verifier with tokenUse "id" if you really want ID tokens.
Client ID not allowed
The token came from a different app client. Add that client ID to the verifier's clientId list, or fix the front end's client ID.
Unable to find a signing key that matches
The kid is not in your pool's JWKS: the token is from another pool, the key rotated and your cache is stale, or the token was forged.
Verification hangs or times out in Lambda
The function cannot reach the public JWKS URL from a private subnet. Add a NAT route, or load the JWKS at deploy time with cacheJwks.
Fresh tokens fail as expired
The server clock is wrong. Sync it with NTP, and allow a few seconds of leeway.
Verifying Cognito JWTs: frequently asked questions
How do I verify a Cognito JWT token?
Check the RS256 signature with your user pool's JWKS key matched by kid, then check iss, token_use, client_id (access token) or aud (ID token), and exp.
How do I verify a Cognito access token?
Use aws-jwt-verify with tokenUse "access" and your clientId in Node.js, or PyJWT without an audience plus checks on token_use and client_id in Python.
How do I verify a Cognito ID token?
Verify the signature and issuer, then check that aud equals your app client ID and token_use is "id". In PyJWT, pass audience=CLIENT_ID.
Why does a Cognito access token have no aud claim?
Cognito puts the app client in client_id instead. An aud claim appears in access tokens only when the app requested a resource binding.
What is the Cognito JWKS URL?
https://cognito-idp.REGION.amazonaws.com/USER_POOL_ID/.well-known/jwks.json. It is public and holds the pool's RS256 public keys.
What is aws-jwt-verify?
AWS's JavaScript library for verifying JWTs from Cognito and other issuers. CognitoJwtVerifier checks signature, issuer, token_use, client ID, expiry, scopes and groups.
How do I verify a Cognito JWT in Python?
Use PyJWT with PyJWKClient for the signing key, jwt.decode with algorithms=["RS256"] and issuer=, then check token_use and client_id or aud.
What is the issuer of a Cognito token?
https://cognito-idp.REGION.amazonaws.com/USER_POOL_ID, for example https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ExaMPle1.
Should my API accept the ID token or the access token?
The access token. It is built for authorization, with scopes and token_use "access". The ID token is for the client app to read user details.
How long is a Cognito token valid?
Access and ID tokens last from 5 minutes to 1 day, often one hour. Refresh tokens default to 30 days and can be 60 minutes to 10 years.
Can I decode a Cognito JWT without verifying it?
Yes, for debugging. The payload is base64url JSON. Never use unverified claims for access decisions.
Does API Gateway verify Cognito tokens for me?
Yes. HTTP API JWT authorizers check signature, issuer, aud or client_id, exp and scopes. REST APIs use a Cognito user pool authorizer.
What does Token use not allowed mean?
aws-jwt-verify received an ID token where you configured access tokens, or the reverse. Send the right token or change tokenUse.
Do Cognito JWTs stop working after sign-out?
A signed JWT stays valid until it expires unless your app checks revocation, so keep access token lifetimes short.
How do I check Cognito groups in a token?
Read the cognito:groups claim after verifying, or pass groups to CognitoJwtVerifier so it enforces membership.
Why does verification fail only in Lambda?
Usually the function cannot reach the JWKS URL from a private subnet, or the verifier is created inside the handler and refetches keys each time.
For readers preparing for an AWS certification
We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.
Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • Security – Specialty (SCS-C03) • Solutions Architect – Associate (SAA-C03).
Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:
1. A backend must confirm that a JWT was issued by its Cognito user pool. What does it verify first?
The RS256 signature, using the public key from the user pool's JWKS endpoint whose kid matches the token header.
2. Which Cognito token should an API accept to authorize calls?
The access token (token_use access), which carries scopes and the client_id of the app client.
3. An API's JWT check passes ID tokens but rejects every access token for a missing audience. What is wrong?
Cognito access tokens carry the app client in client_id, not aud; check client_id for access tokens and aud for ID tokens.
4. A developer wants an HTTP API to validate Cognito tokens without writing code. What should they use?
An API Gateway HTTP API JWT authorizer with the user pool as issuer and the app client ID as audience.
5. A Lambda function verifies tokens but every first request is slow. What improves this?
Create the verifier outside the handler and cache the JWKS (for example with aws-jwt-verify hydrate or cacheJwks).
6. How can an API restrict an endpoint to members of a Cognito group?
Verify the token and check the cognito:groups claim, or configure the verifier's groups option.
Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.
The booking API now verifies access tokens with aws-jwt-verify, checks the customer's group for admin pages, and logs only the reason for a rejection, never the token. Jake asked whether the customers noticed anything. "They notice when it breaks," Ethan said. "This is the part they should never notice."
Ethan also kept the failure tests he wrote while fixing it: one with an ID token, one expired, one from the wrong app client and one with a single character changed. They run before every deploy now. If a library update or a config change ever loosens the checks, the build fails before any customer can find out, and that small file of tests has already caught one mistyped client ID in a staging config.
📌 If you keep one line from this page
Verify the RS256 signature with your pool's JWKS, check iss and token_use, check client_id for access tokens and aud for ID tokens, check exp, and let aws-jwt-verify do all of it in Node.js.
aws-jwt-verify 5.2.1 · PyJWT 2.15.1 · access/ID tokens 5 min to 1 day · refresh 30 days default · October 2026.
Revision note. Written October 22, 2026, with the Cognito and API Gateway documentation of that date and error messages exactly as aws-jwt-verify 5.2.1 and PyJWT 2.15.1 print them. "Trust, but verify," the old saying goes, and with tokens the verifying is the trust.