Amazon Cognito: Validate a Cognito JWT
See more Amazon Cognito Examples
Validate an access token (default) or ID token using the configured pool's JWKS and Chilkat.Jwt/PublicKey. Explicitly allow RS256, select one matching kid, verify the signature, then check issuer, token_use, time claims, and the appropriate client claim: aud for ID tokens, client_id for access tokens. The access-token example also requires an exact scope. A JWT header or payload decoded before signature verification is untrusted.
This example targets the standard Cognito user-pool issuer and RS256 signing. If your pool uses another explicitly configured issuer/signing algorithm, adjust the allowlist and trusted configuration deliberately. Cache JWKS in production and refresh once on an unknown kid to handle rotation; never follow a token-supplied key URL. Verify any nonce you requested at sign-in, and any API-specific resource audience when using resource binding. Offline signature checks cannot detect token revocation or user disablement; enforce your API's revocation/session policy separately. M2M access tokens may not represent a user; this example validates user tokens.
Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.
Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.
Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.
Chilkat Python Downloads
import sys
import chilkat2
success = False
# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
# App settings are trusted configuration. Keep a separate account_key/cache per local user.
app = chilkat2.JsonObject()
app.Strict = True
success = app.LoadFile("qa_data/cognito/app.json")
if (success != True):
print("Could not load Cognito app settings.")
sys.exit()
if ((app.JsonTypeOf("region") != 1) or (app.StringOf("region") == "")):
print("Missing or invalid region.")
sys.exit()
if ((app.JsonTypeOf("user_pool_id") != 1) or (app.StringOf("user_pool_id") == "")):
print("Missing or invalid user_pool_id.")
sys.exit()
if ((app.JsonTypeOf("client_id") != 1) or (app.StringOf("client_id") == "")):
print("Missing or invalid client_id.")
sys.exit()
if ((app.JsonTypeOf("account_key") != 1) or (app.StringOf("account_key") == "")):
print("Missing or invalid account_key.")
sys.exit()
clientId = app.StringOf("client_id")
endpoint = chilkat2.StringBuilder()
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.StringOf("region"))
endpoint.Append(".amazonaws.com/")
http = chilkat2.Http()
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
resp = chilkat2.HttpResponse()
body = chilkat2.JsonObject()
result = chilkat2.JsonObject()
result.Strict = True
cached = chilkat2.JsonObject()
cached.Strict = True
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
if (success != True):
print("Could not load qa_data/tokens/cognito-user.json.")
sys.exit()
if ((cached.JsonTypeOf("client_id") != 1) or (cached.StringOf("client_id") == "")):
print("Missing or invalid client_id.")
sys.exit()
if (cached.StringOf("client_id") != app.StringOf("client_id")):
print("Saved data belongs to another client, pool, or local account.")
sys.exit()
if ((cached.JsonTypeOf("user_pool_id") != 1) or (cached.StringOf("user_pool_id") == "")):
print("Missing or invalid user_pool_id.")
sys.exit()
if (cached.StringOf("user_pool_id") != app.StringOf("user_pool_id")):
print("Saved data belongs to another client, pool, or local account.")
sys.exit()
if ((cached.JsonTypeOf("account_key") != 1) or (cached.StringOf("account_key") == "")):
print("Missing or invalid account_key.")
sys.exit()
if (cached.StringOf("account_key") != app.StringOf("account_key")):
print("Saved data belongs to another client, pool, or local account.")
sys.exit()
# Choose the expected token type independently of the incoming JWT.
expectedUse = "access"
requiredScope = "aws.cognito.signin.user.admin"
if ((expectedUse != "access") and (expectedUse != "id")):
print("Choose access or id.")
sys.exit()
encodedToken = cached.StringOf("access_token")
if (expectedUse == "id"):
encodedToken = cached.StringOf("id_token")
if (((expectedUse == "access") and (cached.JsonTypeOf("access_token") != 1)) or ((expectedUse == "id") and (cached.JsonTypeOf("id_token") != 1)) or (encodedToken == "")):
print("Missing JWT.")
sys.exit()
jwt = chilkat2.Jwt()
header = chilkat2.JsonObject()
header.Strict = True
success = header.Load(jwt.GetHeader(encodedToken))
if (success != True):
print("Invalid JWT header.")
sys.exit()
if (header.StringOf("alg") != "RS256"):
print("Expected RS256; do not trust the token algorithm without an allowlist.")
sys.exit()
if ((header.JsonTypeOf("kid") != 1) or (header.StringOf("kid") == "")):
print("Missing or invalid kid.")
sys.exit()
issuer = chilkat2.StringBuilder()
issuer.Append(endpoint.GetAsString())
issuer.Append(app.StringOf("user_pool_id"))
jwksUrl = chilkat2.StringBuilder()
jwksUrl.Append(issuer.GetAsString())
jwksUrl.Append("/.well-known/jwks.json")
# Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
success = http.HttpNoBody("GET",jwksUrl.GetAsString(),resp)
if (resp.StatusCode != 200):
print("HTTP status: " + str(resp.StatusCode))
success = result.Load(resp.BodyStr)
if (success == True):
print("Error type: " + result.StringOf("__type"))
print("OAuth error: " + result.StringOf("error"))
# Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
sys.exit()
if (success != True):
print("The HTTP exchange did not complete.")
sys.exit()
success = result.Load(resp.BodyStr)
if (success != True):
print("Expected a JSON response.")
sys.exit()
if (result.JsonTypeOf("keys") != 4):
print("Expected a JWKS keys array.")
sys.exit()
i = 0
count = result.SizeOfArray("keys")
matches = 0
jwk = chilkat2.JsonObject()
while i < count :
result.I = i
if (result.StringOf("keys[i].kid") == header.StringOf("kid")):
matches = matches + 1
success = result.ObjectOf2("keys[i]",jwk)
if (success != True):
print("Could not read the matching key.")
sys.exit()
i = i + 1
if (matches != 1):
print("Expected exactly one matching signing key.")
sys.exit()
if ((jwk.StringOf("kty") != "RSA") or (jwk.StringOf("use") != "sig") or (jwk.StringOf("alg") != "RS256")):
print("Unexpected signing-key type, use, or algorithm.")
sys.exit()
publicKey = chilkat2.PublicKey()
success = publicKey.LoadFromString(jwk.Emit())
if (success != True):
print("Could not load the RSA JWK.")
sys.exit()
success = jwt.VerifyJwtPk(encodedToken,publicKey)
if (success != True):
print("Invalid JWT signature.")
sys.exit()
# Only now inspect trusted claims. A valid signature alone is not sufficient.
claims = chilkat2.JsonObject()
claims.Strict = True
success = claims.Load(jwt.GetPayload(encodedToken))
if (success != True):
print("Invalid JWT claims.")
sys.exit()
if (claims.StringOf("iss") != issuer.GetAsString()):
print("JWT issuer mismatch.")
sys.exit()
if (claims.StringOf("token_use") != expectedUse):
print("Wrong token purpose.")
sys.exit()
if ((claims.JsonTypeOf("exp") != 2) or (claims.JsonTypeOf("iat") != 2)):
print("Missing numeric expiration or issue time.")
sys.exit()
if (jwt.IsTimeValid(encodedToken,60) != True):
print("JWT is expired or not yet valid.")
sys.exit()
if (expectedUse == "id"):
if (claims.StringOf("aud") != clientId):
print("ID token audience mismatch.")
sys.exit()
else:
if (claims.StringOf("client_id") != clientId):
print("Access token client mismatch.")
sys.exit()
# Whole-word scope matching, not a substring match.
scopes = chilkat2.StringBuilder()
scopes.Append(" ")
scopes.Append(claims.StringOf("scope"))
scopes.Append(" ")
wantedScope = chilkat2.StringBuilder()
wantedScope.Append(" ")
wantedScope.Append(requiredScope)
wantedScope.Append(" ")
if ((requiredScope != "") and (scopes.Contains(wantedScope.GetAsString(),True) != True)):
print("Required scope is absent.")
sys.exit()
if ((claims.JsonTypeOf("sub") != 1) or (claims.StringOf("sub") == "")):
print("Missing or invalid sub.")
sys.exit()
print("JWT signature and required claims are valid.")
# Apply your application's authorization policy before granting access.