Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

Amazon Cognito: Exchange an ID Token for Temporary AWS Credentials

See more Amazon Cognito Examples

Configure an Identity Pool with the User Pool and app client as an authenticated provider, an authenticated IAM role, and the required trust/permissions policies. Supply the separate Identity Pool ID and region in the code. GetId and GetCredentialsForIdentity use the cognito-identity service and the user's ID token in Logins; they are not signed with administrative IAM credentials. An access token is not a substitute for this ID token.

The provider key is exactly cognito-idp.REGION.amazonaws.com/USER_POOL_ID, with no https:// prefix; it is a literal JSON property name. Both requests carry Logins. Persist the returned IdentityId because it can differ after linking, and retain the identity-pool context. The resulting access key, secret key, session token, and expiration describe temporary AWS credentials, not OAuth tokens. Save them separately and renew before expiration using a current user token. Their permissions come from Identity Pool role mapping/IAM policy; they do not automatically grant Cognito administrator access.

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.

AWS documentation 1 | AWS documentation 2 | AWS documentation 3

Chilkat Lua Downloads

Lua
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

if (cached:json_type_of("id_token") ~= 1) or (cached:string_of("id_token") == "") then
    print("Missing or invalid id_token.")
    return
end

-- Identity Pool region may differ from the User Pool region.
local identityRegion = "us-west-2"
local identityPoolId = "us-west-2:11111111-2222-3333-4444-555555555555"
local identityEndpoint = chilkat.StringBuilder.new()
identityEndpoint:append("https://cognito-identity.")
identityEndpoint:append(identityRegion)
identityEndpoint:append(".amazonaws.com/")
local provider = chilkat.StringBuilder.new()
provider:append("cognito-idp.")
provider:append(app:string_of("region"))
provider:append(".amazonaws.com/")
provider:append(app:string_of("user_pool_id"))
body:update_string("IdentityPoolId", identityPoolId)
body:update_new_object("Logins")
local logins = chilkat.JsonObject.new()
success = body:object_of2("Logins", logins)
if not success then
    print("Could not create the Logins map.")
    return
end

-- AppendString takes a literal property name, preserving periods and the slash.
logins:append_string(provider:get_as_string(), cached:string_of("id_token"))
http:set_request_header("X-Amz-Target", "AWSCognitoIdentityService.GetId")
success = http:http_json("POST", identityEndpoint:get_as_string(), body, "application/x-amz-json-1.1", 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("IdentityId") ~= 1) or (result:string_of("IdentityId") == "") then
    print("Missing or invalid IdentityId.")
    return
end

local identityId = result:string_of("IdentityId")
body:delete("IdentityPoolId")
body:update_string("IdentityId", identityId)
-- Include the same Logins map again; do not accidentally request unauthenticated access.
http:set_request_header("X-Amz-Target", "AWSCognitoIdentityService.GetCredentialsForIdentity")
success = http:http_json("POST", identityEndpoint:get_as_string(), body, "application/x-amz-json-1.1", 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("IdentityId") ~= 1) or (result:string_of("IdentityId") == "") then
    print("Missing or invalid IdentityId.")
    return
end

if (result:json_type_of("Credentials.AccessKeyId") ~= 1) or (result:string_of("Credentials.AccessKeyId") == "") then
    print("Missing or invalid Credentials.AccessKeyId.")
    return
end

if (result:json_type_of("Credentials.SecretKey") ~= 1) or (result:string_of("Credentials.SecretKey") == "") then
    print("Missing or invalid Credentials.SecretKey.")
    return
end

if (result:json_type_of("Credentials.SessionToken") ~= 1) or (result:string_of("Credentials.SessionToken") == "") then
    print("Missing or invalid Credentials.SessionToken.")
    return
end

if result:json_type_of("Credentials.Expiration") ~= 2 then
    print("Missing credential expiration.")
    return
end

local temporary = chilkat.JsonObject.new()
temporary:update_string("access_key", result:string_of("Credentials.AccessKeyId"))
temporary:update_string("secret_key", result:string_of("Credentials.SecretKey"))
temporary:update_string("session_token", result:string_of("Credentials.SessionToken"))
-- Expiration is a Unix timestamp; preserve its decimal text rather than using int64.
temporary:update_string("expiration_unix", result:string_of("Credentials.Expiration"))
temporary:update_string("identity_id", result:string_of("IdentityId"))
temporary:update_string("identity_pool_id", identityPoolId)
temporary:update_string("client_id", app:string_of("client_id"))
temporary:update_string("user_pool_id", app:string_of("user_pool_id"))
temporary:update_string("account_key", app:string_of("account_key"))
local temporarytemporaryAWScredentials = chilkat.FileAccess.new()
success = temporarytemporaryAWScredentials:dir_ensure_exists("qa_data/tokens")
if not success then
    print("Could not create the private cache directory.")
    return
end

if temporarytemporaryAWScredentials:file_exists("qa_data/tokens/cognito-identity.json") then
    success = temporarytemporaryAWScredentials:file_copy("qa_data/tokens/cognito-identity.json", "qa_data/tokens/cognito-identity.json.bak", false)
    if not success then
        print("Could not back up the existing cache.")
        return
    end
end

success = temporary:write_file("qa_data/tokens/cognito-identity.json")
if not success then
    print("Could not save temporary AWS credentials; preserve any previous backup.")
    return
end

print("Identity ID: " .. result:string_of("IdentityId"))
print("Temporary AWS credentials saved privately.")
-- Renew by repeating the exchange with a current ID token before Expiration.
-- Use these credentials only for actions allowed by the selected Identity Pool IAM role.