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

CkPerl
use chilkat();

$success = 0;

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
#  App settings are trusted configuration. Keep a separate account_key/cache per local user.
$app = chilkat::CkJsonObject->new();
$app->put_Strict(1);
$success = $app->LoadFile("qa_data/cognito/app.json");
if ($success != 1) {
    print "Could not load Cognito app settings." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("region") != 1) or ($app->stringOf("region") == "")) {
    print "Missing or invalid region." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("user_pool_id") != 1) or ($app->stringOf("user_pool_id") == "")) {
    print "Missing or invalid user_pool_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("client_id") != 1) or ($app->stringOf("client_id") == "")) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("account_key") != 1) or ($app->stringOf("account_key") == "")) {
    print "Missing or invalid account_key." . "\r\n";
    exit;
}

$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(1);
$http->put_FollowRedirects(0);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(60);
$resp = chilkat::CkHttpResponse->new();
$body = chilkat::CkJsonObject->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
$cached = chilkat::CkJsonObject->new();
$cached->put_Strict(1);
$success = $cached->LoadFile("qa_data/tokens/cognito-user.json");
if ($success != 1) {
    print "Could not load qa_data/tokens/cognito-user.json." . "\r\n";
    exit;
}

if (($cached->JsonTypeOf("client_id") != 1) or ($cached->stringOf("client_id") == "")) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

if ($cached->stringOf("client_id") != $app->stringOf("client_id")) {
    print "Saved data belongs to another client, pool, or local account." . "\r\n";
    exit;
}

if (($cached->JsonTypeOf("user_pool_id") != 1) or ($cached->stringOf("user_pool_id") == "")) {
    print "Missing or invalid user_pool_id." . "\r\n";
    exit;
}

if ($cached->stringOf("user_pool_id") != $app->stringOf("user_pool_id")) {
    print "Saved data belongs to another client, pool, or local account." . "\r\n";
    exit;
}

if (($cached->JsonTypeOf("account_key") != 1) or ($cached->stringOf("account_key") == "")) {
    print "Missing or invalid account_key." . "\r\n";
    exit;
}

if ($cached->stringOf("account_key") != $app->stringOf("account_key")) {
    print "Saved data belongs to another client, pool, or local account." . "\r\n";
    exit;
}

if (($cached->JsonTypeOf("id_token") != 1) or ($cached->stringOf("id_token") == "")) {
    print "Missing or invalid id_token." . "\r\n";
    exit;
}

#  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 != 1) {
    print "Could not create the Logins map." . "\r\n";
    exit;
}

#  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() . "\r\n";
    $success = $result->Load($resp->bodyStr());
    if ($success == 1) {
        print "Error type: " . $result->stringOf("__type") . "\r\n";
        print "OAuth error: " . $result->stringOf("error") . "\r\n";
    }

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

if ($success != 1) {
    print "The HTTP exchange did not complete." . "\r\n";
    exit;
}

$success = $result->Load($resp->bodyStr());
if ($success != 1) {
    print "Expected a JSON response." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("IdentityId") != 1) or ($result->stringOf("IdentityId") == "")) {
    print "Missing or invalid IdentityId." . "\r\n";
    exit;
}

$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() . "\r\n";
    $success = $result->Load($resp->bodyStr());
    if ($success == 1) {
        print "Error type: " . $result->stringOf("__type") . "\r\n";
        print "OAuth error: " . $result->stringOf("error") . "\r\n";
    }

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

if ($success != 1) {
    print "The HTTP exchange did not complete." . "\r\n";
    exit;
}

$success = $result->Load($resp->bodyStr());
if ($success != 1) {
    print "Expected a JSON response." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("IdentityId") != 1) or ($result->stringOf("IdentityId") == "")) {
    print "Missing or invalid IdentityId." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("Credentials.AccessKeyId") != 1) or ($result->stringOf("Credentials.AccessKeyId") == "")) {
    print "Missing or invalid Credentials.AccessKeyId." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("Credentials.SecretKey") != 1) or ($result->stringOf("Credentials.SecretKey") == "")) {
    print "Missing or invalid Credentials.SecretKey." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("Credentials.SessionToken") != 1) or ($result->stringOf("Credentials.SessionToken") == "")) {
    print "Missing or invalid Credentials.SessionToken." . "\r\n";
    exit;
}

if ($result->JsonTypeOf("Credentials.Expiration") != 2) {
    print "Missing credential expiration." . "\r\n";
    exit;
}

$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 != 1) {
    print "Could not create the private cache directory." . "\r\n";
    exit;
}

if ($temporarytemporaryAWScredentials->FileExists("qa_data/tokens/cognito-identity.json") == 1) {
    $success = $temporarytemporaryAWScredentials->FileCopy("qa_data/tokens/cognito-identity.json","qa_data/tokens/cognito-identity.json.bak",0);
    if ($success != 1) {
        print "Could not back up the existing cache." . "\r\n";
        exit;
    }

}

$success = $temporary->WriteFile("qa_data/tokens/cognito-identity.json");
if ($success != 1) {
    print "Could not save temporary AWS credentials; preserve any previous backup." . "\r\n";
    exit;
}

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