Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

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 = Chilkat::CkJsonObject.new()
app.put_Strict(true)
success = app.LoadFile("qa_data/cognito/app.json")
if (success != true)
    print "Could not load Cognito app settings." + "\n";
    exit
end

if ((app.JsonTypeOf("region") != 1) or (app.stringOf("region") == ""))
    print "Missing or invalid region." + "\n";
    exit
end

if ((app.JsonTypeOf("user_pool_id") != 1) or (app.stringOf("user_pool_id") == ""))
    print "Missing or invalid user_pool_id." + "\n";
    exit
end

if ((app.JsonTypeOf("client_id") != 1) or (app.stringOf("client_id") == ""))
    print "Missing or invalid client_id." + "\n";
    exit
end

if ((app.JsonTypeOf("account_key") != 1) or (app.stringOf("account_key") == ""))
    print "Missing or invalid account_key." + "\n";
    exit
end

clientId = app.stringOf("client_id")
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.stringOf("region"))
endpoint.Append(".amazonaws.com/")
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(60)
resp = Chilkat::CkHttpResponse.new()
body = Chilkat::CkJsonObject.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
cached = Chilkat::CkJsonObject.new()
cached.put_Strict(true)
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
if (success != true)
    print "Could not load qa_data/tokens/cognito-user.json." + "\n";
    exit
end

if ((cached.JsonTypeOf("client_id") != 1) or (cached.stringOf("client_id") == ""))
    print "Missing or invalid client_id." + "\n";
    exit
end

if (cached.stringOf("client_id") != app.stringOf("client_id"))
    print "Saved data belongs to another client, pool, or local account." + "\n";
    exit
end

if ((cached.JsonTypeOf("user_pool_id") != 1) or (cached.stringOf("user_pool_id") == ""))
    print "Missing or invalid user_pool_id." + "\n";
    exit
end

if (cached.stringOf("user_pool_id") != app.stringOf("user_pool_id"))
    print "Saved data belongs to another client, pool, or local account." + "\n";
    exit
end

if ((cached.JsonTypeOf("account_key") != 1) or (cached.stringOf("account_key") == ""))
    print "Missing or invalid account_key." + "\n";
    exit
end

if (cached.stringOf("account_key") != app.stringOf("account_key"))
    print "Saved data belongs to another client, pool, or local account." + "\n";
    exit
end

if ((cached.JsonTypeOf("id_token") != 1) or (cached.stringOf("id_token") == ""))
    print "Missing or invalid id_token." + "\n";
    exit
end

#  Identity Pool region may differ from the User Pool region.
identityRegion = "us-west-2"
identityPoolId = "us-west-2:11111111-2222-3333-4444-555555555555"
identityEndpoint = Chilkat::CkStringBuilder.new()
identityEndpoint.Append("https://cognito-identity.")
identityEndpoint.Append(identityRegion)
identityEndpoint.Append(".amazonaws.com/")
provider = Chilkat::CkStringBuilder.new()
provider.Append("cognito-idp.")
provider.Append(app.stringOf("region"))
provider.Append(".amazonaws.com/")
provider.Append(app.stringOf("user_pool_id"))
body.UpdateString("IdentityPoolId",identityPoolId)
body.UpdateNewObject("Logins")
logins = Chilkat::CkJsonObject.new()
success = body.ObjectOf2("Logins",logins)
if (success != true)
    print "Could not create the Logins map." + "\n";
    exit
end

#  AppendString takes a literal property name, preserving periods and the slash.
logins.AppendString(provider.getAsString(),cached.stringOf("id_token"))
http.SetRequestHeader("X-Amz-Target","AWSCognitoIdentityService.GetId")
success = http.HttpJson("POST",identityEndpoint.getAsString(),body,"application/x-amz-json-1.1",resp)
if (resp.get_StatusCode() != 200)
    print "HTTP status: " + resp.get_StatusCode().to_s() + "\n";
    success = result.Load(resp.bodyStr())
    if (success == true)
        print "Error type: " + result.stringOf("__type") + "\n";
        print "OAuth error: " + result.stringOf("error") + "\n";
    end

    #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    exit
end

if (success != true)
    print "The HTTP exchange did not complete." + "\n";
    exit
end

success = result.Load(resp.bodyStr())
if (success != true)
    print "Expected a JSON response." + "\n";
    exit
end

if ((result.JsonTypeOf("IdentityId") != 1) or (result.stringOf("IdentityId") == ""))
    print "Missing or invalid IdentityId." + "\n";
    exit
end

identityId = result.stringOf("IdentityId")
body.Delete("IdentityPoolId")
body.UpdateString("IdentityId",identityId)
#  Include the same Logins map again; do not accidentally request unauthenticated access.
http.SetRequestHeader("X-Amz-Target","AWSCognitoIdentityService.GetCredentialsForIdentity")
success = http.HttpJson("POST",identityEndpoint.getAsString(),body,"application/x-amz-json-1.1",resp)
if (resp.get_StatusCode() != 200)
    print "HTTP status: " + resp.get_StatusCode().to_s() + "\n";
    success = result.Load(resp.bodyStr())
    if (success == true)
        print "Error type: " + result.stringOf("__type") + "\n";
        print "OAuth error: " + result.stringOf("error") + "\n";
    end

    #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    exit
end

if (success != true)
    print "The HTTP exchange did not complete." + "\n";
    exit
end

success = result.Load(resp.bodyStr())
if (success != true)
    print "Expected a JSON response." + "\n";
    exit
end

if ((result.JsonTypeOf("IdentityId") != 1) or (result.stringOf("IdentityId") == ""))
    print "Missing or invalid IdentityId." + "\n";
    exit
end

if ((result.JsonTypeOf("Credentials.AccessKeyId") != 1) or (result.stringOf("Credentials.AccessKeyId") == ""))
    print "Missing or invalid Credentials.AccessKeyId." + "\n";
    exit
end

if ((result.JsonTypeOf("Credentials.SecretKey") != 1) or (result.stringOf("Credentials.SecretKey") == ""))
    print "Missing or invalid Credentials.SecretKey." + "\n";
    exit
end

if ((result.JsonTypeOf("Credentials.SessionToken") != 1) or (result.stringOf("Credentials.SessionToken") == ""))
    print "Missing or invalid Credentials.SessionToken." + "\n";
    exit
end

if (result.JsonTypeOf("Credentials.Expiration") != 2)
    print "Missing credential expiration." + "\n";
    exit
end

temporary = Chilkat::CkJsonObject.new()
temporary.UpdateString("access_key",result.stringOf("Credentials.AccessKeyId"))
temporary.UpdateString("secret_key",result.stringOf("Credentials.SecretKey"))
temporary.UpdateString("session_token",result.stringOf("Credentials.SessionToken"))
#  Expiration is a Unix timestamp; preserve its decimal text rather than using int64.
temporary.UpdateString("expiration_unix",result.stringOf("Credentials.Expiration"))
temporary.UpdateString("identity_id",result.stringOf("IdentityId"))
temporary.UpdateString("identity_pool_id",identityPoolId)
temporary.UpdateString("client_id",app.stringOf("client_id"))
temporary.UpdateString("user_pool_id",app.stringOf("user_pool_id"))
temporary.UpdateString("account_key",app.stringOf("account_key"))
temporarytemporaryAWScredentials = Chilkat::CkFileAccess.new()
success = temporarytemporaryAWScredentials.DirEnsureExists("qa_data/tokens")
if (success != true)
    print "Could not create the private cache directory." + "\n";
    exit
end

if (temporarytemporaryAWScredentials.FileExists("qa_data/tokens/cognito-identity.json") == true)
    success = temporarytemporaryAWScredentials.FileCopy("qa_data/tokens/cognito-identity.json","qa_data/tokens/cognito-identity.json.bak",false)
    if (success != true)
        print "Could not back up the existing cache." + "\n";
        exit
    end

end

success = temporary.WriteFile("qa_data/tokens/cognito-identity.json")
if (success != true)
    print "Could not save temporary AWS credentials; preserve any previous backup." + "\n";
    exit
end

print "Identity ID: " + result.stringOf("IdentityId") + "\n";
print "Temporary AWS credentials saved privately." + "\n";
#  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.