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

AutoIt
Local $bSuccess = False

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  App settings are trusted configuration. Keep a separate account_key/cache per local user.
$oApp = ObjCreate("Chilkat.JsonObject")
$oApp.Strict = True
$bSuccess = $oApp.LoadFile("qa_data/cognito/app.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load Cognito app settings." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("region") <> 1) Or ($oApp.StringOf("region") = "")) Then
    ConsoleWrite("Missing or invalid region." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("user_pool_id") <> 1) Or ($oApp.StringOf("user_pool_id") = "")) Then
    ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("client_id") <> 1) Or ($oApp.StringOf("client_id") = "")) Then
    ConsoleWrite("Missing or invalid client_id." & @CRLF)
    Exit
EndIf

If (($oApp.JsonTypeOf("account_key") <> 1) Or ($oApp.StringOf("account_key") = "")) Then
    ConsoleWrite("Missing or invalid account_key." & @CRLF)
    Exit
EndIf

Local $sClientId = $oApp.StringOf("client_id")
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://cognito-idp.")
$oEndpoint.Append($oApp.StringOf("region"))
$oEndpoint.Append(".amazonaws.com/")
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 60
$oResp = ObjCreate("Chilkat.HttpResponse")
$oBody = ObjCreate("Chilkat.JsonObject")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oCached = ObjCreate("Chilkat.JsonObject")
$oCached.Strict = True
$bSuccess = $oCached.LoadFile("qa_data/tokens/cognito-user.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load qa_data/tokens/cognito-user.json." & @CRLF)
    Exit
EndIf

If (($oCached.JsonTypeOf("client_id") <> 1) Or ($oCached.StringOf("client_id") = "")) Then
    ConsoleWrite("Missing or invalid client_id." & @CRLF)
    Exit
EndIf

If ($oCached.StringOf("client_id") <> $oApp.StringOf("client_id")) Then
    ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
    Exit
EndIf

If (($oCached.JsonTypeOf("user_pool_id") <> 1) Or ($oCached.StringOf("user_pool_id") = "")) Then
    ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
    Exit
EndIf

If ($oCached.StringOf("user_pool_id") <> $oApp.StringOf("user_pool_id")) Then
    ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
    Exit
EndIf

If (($oCached.JsonTypeOf("account_key") <> 1) Or ($oCached.StringOf("account_key") = "")) Then
    ConsoleWrite("Missing or invalid account_key." & @CRLF)
    Exit
EndIf

If ($oCached.StringOf("account_key") <> $oApp.StringOf("account_key")) Then
    ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
    Exit
EndIf

If (($oCached.JsonTypeOf("id_token") <> 1) Or ($oCached.StringOf("id_token") = "")) Then
    ConsoleWrite("Missing or invalid id_token." & @CRLF)
    Exit
EndIf

;  Identity Pool region may differ from the User Pool region.
Local $sIdentityRegion = "us-west-2"
Local $sIdentityPoolId = "us-west-2:11111111-2222-3333-4444-555555555555"
$oIdentityEndpoint = ObjCreate("Chilkat.StringBuilder")
$oIdentityEndpoint.Append("https://cognito-identity.")
$oIdentityEndpoint.Append($sIdentityRegion)
$oIdentityEndpoint.Append(".amazonaws.com/")
$oProvider = ObjCreate("Chilkat.StringBuilder")
$oProvider.Append("cognito-idp.")
$oProvider.Append($oApp.StringOf("region"))
$oProvider.Append(".amazonaws.com/")
$oProvider.Append($oApp.StringOf("user_pool_id"))
$oBody.UpdateString("IdentityPoolId",$sIdentityPoolId)
$oBody.UpdateNewObject("Logins")
$oLogins = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oBody.ObjectOf2("Logins",$oLogins)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the Logins map." & @CRLF)
    Exit
EndIf

;  AppendString takes a literal property name, preserving periods and the slash.
$oLogins.AppendString($oProvider.GetAsString(),$oCached.StringOf("id_token"))
$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityService.GetId"
$bSuccess = $oHttp.HttpJson("POST",$oIdentityEndpoint.GetAsString(),$oBody,"application/x-amz-json-1.1",$oResp)
If ($oResp.StatusCode <> 200) Then
    ConsoleWrite("HTTP status: " & $oResp.StatusCode & @CRLF)
    $bSuccess = $oResult.Load($oResp.BodyStr)
    If ($bSuccess = True) Then
        ConsoleWrite("Error type: " & $oResult.StringOf("__type") & @CRLF)
        ConsoleWrite("OAuth error: " & $oResult.StringOf("error") & @CRLF)
    EndIf

    ;  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("The HTTP exchange did not complete." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a JSON response." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("IdentityId") <> 1) Or ($oResult.StringOf("IdentityId") = "")) Then
    ConsoleWrite("Missing or invalid IdentityId." & @CRLF)
    Exit
EndIf

Local $sIdentityId = $oResult.StringOf("IdentityId")
$oBody.Delete("IdentityPoolId")
$oBody.UpdateString("IdentityId",$sIdentityId)
;  Include the same Logins map again; do not accidentally request unauthenticated access.
$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityService.GetCredentialsForIdentity"
$bSuccess = $oHttp.HttpJson("POST",$oIdentityEndpoint.GetAsString(),$oBody,"application/x-amz-json-1.1",$oResp)
If ($oResp.StatusCode <> 200) Then
    ConsoleWrite("HTTP status: " & $oResp.StatusCode & @CRLF)
    $bSuccess = $oResult.Load($oResp.BodyStr)
    If ($bSuccess = True) Then
        ConsoleWrite("Error type: " & $oResult.StringOf("__type") & @CRLF)
        ConsoleWrite("OAuth error: " & $oResult.StringOf("error") & @CRLF)
    EndIf

    ;  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("The HTTP exchange did not complete." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected a JSON response." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("IdentityId") <> 1) Or ($oResult.StringOf("IdentityId") = "")) Then
    ConsoleWrite("Missing or invalid IdentityId." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("Credentials.AccessKeyId") <> 1) Or ($oResult.StringOf("Credentials.AccessKeyId") = "")) Then
    ConsoleWrite("Missing or invalid Credentials.AccessKeyId." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("Credentials.SecretKey") <> 1) Or ($oResult.StringOf("Credentials.SecretKey") = "")) Then
    ConsoleWrite("Missing or invalid Credentials.SecretKey." & @CRLF)
    Exit
EndIf

If (($oResult.JsonTypeOf("Credentials.SessionToken") <> 1) Or ($oResult.StringOf("Credentials.SessionToken") = "")) Then
    ConsoleWrite("Missing or invalid Credentials.SessionToken." & @CRLF)
    Exit
EndIf

If ($oResult.JsonTypeOf("Credentials.Expiration") <> 2) Then
    ConsoleWrite("Missing credential expiration." & @CRLF)
    Exit
EndIf

$oTemporary = ObjCreate("Chilkat.JsonObject")
$oTemporary.UpdateString("access_key",$oResult.StringOf("Credentials.AccessKeyId"))
$oTemporary.UpdateString("secret_key",$oResult.StringOf("Credentials.SecretKey"))
$oTemporary.UpdateString("session_token",$oResult.StringOf("Credentials.SessionToken"))
;  Expiration is a Unix timestamp; preserve its decimal text rather than using int64.
$oTemporary.UpdateString("expiration_unix",$oResult.StringOf("Credentials.Expiration"))
$oTemporary.UpdateString("identity_id",$oResult.StringOf("IdentityId"))
$oTemporary.UpdateString("identity_pool_id",$sIdentityPoolId)
$oTemporary.UpdateString("client_id",$oApp.StringOf("client_id"))
$oTemporary.UpdateString("user_pool_id",$oApp.StringOf("user_pool_id"))
$oTemporary.UpdateString("account_key",$oApp.StringOf("account_key"))
$oTemporarytemporaryAWScredentials = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oTemporarytemporaryAWScredentials.DirEnsureExists("qa_data/tokens")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the private cache directory." & @CRLF)
    Exit
EndIf

If ($oTemporarytemporaryAWScredentials.FileExists("qa_data/tokens/cognito-identity.json") = True) Then
    $bSuccess = $oTemporarytemporaryAWScredentials.FileCopy("qa_data/tokens/cognito-identity.json","qa_data/tokens/cognito-identity.json.bak",False)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not back up the existing cache." & @CRLF)
        Exit
    EndIf

EndIf

$bSuccess = $oTemporary.WriteFile("qa_data/tokens/cognito-identity.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save temporary AWS credentials; preserve any previous backup." & @CRLF)
    Exit
EndIf

ConsoleWrite("Identity ID: " & $oResult.StringOf("IdentityId") & @CRLF)
ConsoleWrite("Temporary AWS credentials saved privately." & @CRLF)
;  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.