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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- App settings are trusted configuration. Keep a separate account_key/cache per local user.
local app = chilkat.JsonObject.new()
app.strict = true
success = app:load_file("qa_data/cognito/app.json")
if not success then
print("Could not load Cognito app settings.")
return
end
if (app:json_type_of("region") ~= 1) or (app:string_of("region") == "") then
print("Missing or invalid region.")
return
end
if (app:json_type_of("user_pool_id") ~= 1) or (app:string_of("user_pool_id") == "") then
print("Missing or invalid user_pool_id.")
return
end
if (app:json_type_of("client_id") ~= 1) or (app:string_of("client_id") == "") then
print("Missing or invalid client_id.")
return
end
if (app:json_type_of("account_key") ~= 1) or (app:string_of("account_key") == "") then
print("Missing or invalid account_key.")
return
end
local clientId = app:string_of("client_id")
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://cognito-idp.")
endpoint:append(app:string_of("region"))
endpoint:append(".amazonaws.com/")
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 60
local resp = chilkat.HttpResponse.new()
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
local cached = chilkat.JsonObject.new()
cached.strict = true
success = cached:load_file("qa_data/tokens/cognito-user.json")
if not success then
print("Could not load qa_data/tokens/cognito-user.json.")
return
end
if (cached:json_type_of("client_id") ~= 1) or (cached:string_of("client_id") == "") then
print("Missing or invalid client_id.")
return
end
if cached:string_of("client_id") ~= app:string_of("client_id") then
print("Saved data belongs to another client, pool, or local account.")
return
end
if (cached:json_type_of("user_pool_id") ~= 1) or (cached:string_of("user_pool_id") == "") then
print("Missing or invalid user_pool_id.")
return
end
if cached:string_of("user_pool_id") ~= app:string_of("user_pool_id") then
print("Saved data belongs to another client, pool, or local account.")
return
end
if (cached:json_type_of("account_key") ~= 1) or (cached:string_of("account_key") == "") then
print("Missing or invalid account_key.")
return
end
if cached:string_of("account_key") ~= app:string_of("account_key") then
print("Saved data belongs to another client, pool, or local account.")
return
end
-- Choose the expected token type independently of the incoming JWT.
local expectedUse = "access"
local requiredScope = "aws.cognito.signin.user.admin"
if (expectedUse ~= "access") and (expectedUse ~= "id") then
print("Choose access or id.")
return
end
local encodedToken = cached:string_of("access_token")
if expectedUse == "id" then
encodedToken = cached:string_of("id_token")
end
if ((expectedUse == "access") and (cached:json_type_of("access_token") ~= 1)) or (((expectedUse == "id") and (cached:json_type_of("id_token") ~= 1)) or (encodedToken == "")) then
print("Missing JWT.")
return
end
local jwt = chilkat.Jwt.new()
local header = chilkat.JsonObject.new()
header.strict = true
success = header:load(jwt:get_header(encodedToken))
if not success then
print("Invalid JWT header.")
return
end
if header:string_of("alg") ~= "RS256" then
print("Expected RS256; do not trust the token algorithm without an allowlist.")
return
end
if (header:json_type_of("kid") ~= 1) or (header:string_of("kid") == "") then
print("Missing or invalid kid.")
return
end
local issuer = chilkat.StringBuilder.new()
issuer:append(endpoint:get_as_string())
issuer:append(app:string_of("user_pool_id"))
local jwksUrl = chilkat.StringBuilder.new()
jwksUrl:append(issuer:get_as_string())
jwksUrl:append("/.well-known/jwks.json")
-- Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
success = http:http_no_body("GET", jwksUrl:get_as_string(), resp)
if resp.status_code ~= 200 then
print("HTTP status: " .. resp.status_code)
success = result:load(resp.body_str)
if success then
print("Error type: " .. result:string_of("__type"))
print("OAuth error: " .. result:string_of("error"))
end
-- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return
end
if not success then
print("The HTTP exchange did not complete.")
return
end
success = result:load(resp.body_str)
if not success then
print("Expected a JSON response.")
return
end
if result:json_type_of("keys") ~= 4 then
print("Expected a JWKS keys array.")
return
end
local i = 0
local count = result:size_of_array("keys")
local matches = 0
local jwk = chilkat.JsonObject.new()
while i < count do
result.i = i
if result:string_of("keys[i].kid") == header:string_of("kid") then
matches = matches + 1
success = result:object_of2("keys[i]", jwk)
if not success then
print("Could not read the matching key.")
return
end
end
i = i + 1
end
if matches ~= 1 then
print("Expected exactly one matching signing key.")
return
end
if (jwk:string_of("kty") ~= "RSA") or ((jwk:string_of("use") ~= "sig") or (jwk:string_of("alg") ~= "RS256")) then
print("Unexpected signing-key type, use, or algorithm.")
return
end
local publicKey = chilkat.PublicKey.new()
success = publicKey:load_from_string(jwk:emit())
if not success then
print("Could not load the RSA JWK.")
return
end
success = jwt:verify_jwt_pk(encodedToken, publicKey)
if not success then
print("Invalid JWT signature.")
return
end
-- Only now inspect trusted claims. A valid signature alone is not sufficient.
local claims = chilkat.JsonObject.new()
claims.strict = true
success = claims:load(jwt:get_payload(encodedToken))
if not success then
print("Invalid JWT claims.")
return
end
if claims:string_of("iss") ~= issuer:get_as_string() then
print("JWT issuer mismatch.")
return
end
if claims:string_of("token_use") ~= expectedUse then
print("Wrong token purpose.")
return
end
if (claims:json_type_of("exp") ~= 2) or (claims:json_type_of("iat") ~= 2) then
print("Missing numeric expiration or issue time.")
return
end
if not jwt:is_time_valid(encodedToken, 60) then
print("JWT is expired or not yet valid.")
return
end
if expectedUse == "id" then
if claims:string_of("aud") ~= clientId then
print("ID token audience mismatch.")
return
end
else
if claims:string_of("client_id") ~= clientId then
print("Access token client mismatch.")
return
end
-- Whole-word scope matching, not a substring match.
local scopes = chilkat.StringBuilder.new()
scopes:append(" ")
scopes:append(claims:string_of("scope"))
scopes:append(" ")
local wantedScope = chilkat.StringBuilder.new()
wantedScope:append(" ")
wantedScope:append(requiredScope)
wantedScope:append(" ")
if (requiredScope ~= "") and (not scopes:contains(wantedScope:get_as_string(), true)) then
print("Required scope is absent.")
return
end
end
if (claims:json_type_of("sub") ~= 1) or (claims:string_of("sub") == "") then
print("Missing or invalid sub.")
return
end
print("JWT signature and required claims are valid.")
-- Apply your application's authorization policy before granting access.