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

Xojo Plugin
Dim success As Boolean
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.
Dim app As New Chilkat.JsonObject
app.Strict = True
success = app.LoadFile("qa_data/cognito/app.json")
If (success <> True) Then
    System.DebugLog("Could not load Cognito app settings.")
    Return
End If

If ((app.JsonTypeOf("region") <> 1) Or (app.StringOf("region") = "")) Then
    System.DebugLog("Missing or invalid region.")
    Return
End If

If ((app.JsonTypeOf("user_pool_id") <> 1) Or (app.StringOf("user_pool_id") = "")) Then
    System.DebugLog("Missing or invalid user_pool_id.")
    Return
End If

If ((app.JsonTypeOf("client_id") <> 1) Or (app.StringOf("client_id") = "")) Then
    System.DebugLog("Missing or invalid client_id.")
    Return
End If

If ((app.JsonTypeOf("account_key") <> 1) Or (app.StringOf("account_key") = "")) Then
    System.DebugLog("Missing or invalid account_key.")
    Return
End If

Dim clientId As String
clientId = app.StringOf("client_id")
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("https://cognito-idp.")
success = endpoint.Append(app.StringOf("region"))
success = endpoint.Append(".amazonaws.com/")
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
Dim resp As New Chilkat.HttpResponse
Dim body As New Chilkat.JsonObject
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim cached As New Chilkat.JsonObject
cached.Strict = True
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
If (success <> True) Then
    System.DebugLog("Could not load qa_data/tokens/cognito-user.json.")
    Return
End If

If ((cached.JsonTypeOf("client_id") <> 1) Or (cached.StringOf("client_id") = "")) Then
    System.DebugLog("Missing or invalid client_id.")
    Return
End If

If (cached.StringOf("client_id") <> app.StringOf("client_id")) Then
    System.DebugLog("Saved data belongs to another client, pool, or local account.")
    Return
End If

If ((cached.JsonTypeOf("user_pool_id") <> 1) Or (cached.StringOf("user_pool_id") = "")) Then
    System.DebugLog("Missing or invalid user_pool_id.")
    Return
End If

If (cached.StringOf("user_pool_id") <> app.StringOf("user_pool_id")) Then
    System.DebugLog("Saved data belongs to another client, pool, or local account.")
    Return
End If

If ((cached.JsonTypeOf("account_key") <> 1) Or (cached.StringOf("account_key") = "")) Then
    System.DebugLog("Missing or invalid account_key.")
    Return
End If

If (cached.StringOf("account_key") <> app.StringOf("account_key")) Then
    System.DebugLog("Saved data belongs to another client, pool, or local account.")
    Return
End If

If ((cached.JsonTypeOf("id_token") <> 1) Or (cached.StringOf("id_token") = "")) Then
    System.DebugLog("Missing or invalid id_token.")
    Return
End If

//  Identity Pool region may differ from the User Pool region.
Dim identityRegion As String
identityRegion = "us-west-2"
Dim identityPoolId As String
identityPoolId = "us-west-2:11111111-2222-3333-4444-555555555555"
Dim identityEndpoint As New Chilkat.StringBuilder
success = identityEndpoint.Append("https://cognito-identity.")
success = identityEndpoint.Append(identityRegion)
success = identityEndpoint.Append(".amazonaws.com/")
Dim provider As New Chilkat.StringBuilder
success = provider.Append("cognito-idp.")
success = provider.Append(app.StringOf("region"))
success = provider.Append(".amazonaws.com/")
success = provider.Append(app.StringOf("user_pool_id"))
success = body.UpdateString("IdentityPoolId",identityPoolId)
success = body.UpdateNewObject("Logins")
Dim logins As New Chilkat.JsonObject
success = body.ObjectOf2("Logins",logins)
If (success <> True) Then
    System.DebugLog("Could not create the Logins map.")
    Return
End If

//  AppendString takes a literal property name, preserving periods and the slash.
success = 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.StatusCode <> 200) Then
    System.DebugLog("HTTP status: " + Str(resp.StatusCode))
    success = result.Load(resp.BodyStr)
    If (success = True) Then
        System.DebugLog("Error type: " + result.StringOf("__type"))
        System.DebugLog("OAuth error: " + result.StringOf("error"))
    End If

    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Return
End If

If (success <> True) Then
    System.DebugLog("The HTTP exchange did not complete.")
    Return
End If

success = result.Load(resp.BodyStr)
If (success <> True) Then
    System.DebugLog("Expected a JSON response.")
    Return
End If

If ((result.JsonTypeOf("IdentityId") <> 1) Or (result.StringOf("IdentityId") = "")) Then
    System.DebugLog("Missing or invalid IdentityId.")
    Return
End If

Dim identityId As String
identityId = result.StringOf("IdentityId")
success = body.Delete("IdentityPoolId")
success = 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.StatusCode <> 200) Then
    System.DebugLog("HTTP status: " + Str(resp.StatusCode))
    success = result.Load(resp.BodyStr)
    If (success = True) Then
        System.DebugLog("Error type: " + result.StringOf("__type"))
        System.DebugLog("OAuth error: " + result.StringOf("error"))
    End If

    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Return
End If

If (success <> True) Then
    System.DebugLog("The HTTP exchange did not complete.")
    Return
End If

success = result.Load(resp.BodyStr)
If (success <> True) Then
    System.DebugLog("Expected a JSON response.")
    Return
End If

If ((result.JsonTypeOf("IdentityId") <> 1) Or (result.StringOf("IdentityId") = "")) Then
    System.DebugLog("Missing or invalid IdentityId.")
    Return
End If

If ((result.JsonTypeOf("Credentials.AccessKeyId") <> 1) Or (result.StringOf("Credentials.AccessKeyId") = "")) Then
    System.DebugLog("Missing or invalid Credentials.AccessKeyId.")
    Return
End If

If ((result.JsonTypeOf("Credentials.SecretKey") <> 1) Or (result.StringOf("Credentials.SecretKey") = "")) Then
    System.DebugLog("Missing or invalid Credentials.SecretKey.")
    Return
End If

If ((result.JsonTypeOf("Credentials.SessionToken") <> 1) Or (result.StringOf("Credentials.SessionToken") = "")) Then
    System.DebugLog("Missing or invalid Credentials.SessionToken.")
    Return
End If

If (result.JsonTypeOf("Credentials.Expiration") <> 2) Then
    System.DebugLog("Missing credential expiration.")
    Return
End If

Dim temporary As New Chilkat.JsonObject
success = temporary.UpdateString("access_key",result.StringOf("Credentials.AccessKeyId"))
success = temporary.UpdateString("secret_key",result.StringOf("Credentials.SecretKey"))
success = temporary.UpdateString("session_token",result.StringOf("Credentials.SessionToken"))
//  Expiration is a Unix timestamp; preserve its decimal text rather than using int64.
success = temporary.UpdateString("expiration_unix",result.StringOf("Credentials.Expiration"))
success = temporary.UpdateString("identity_id",result.StringOf("IdentityId"))
success = temporary.UpdateString("identity_pool_id",identityPoolId)
success = temporary.UpdateString("client_id",app.StringOf("client_id"))
success = temporary.UpdateString("user_pool_id",app.StringOf("user_pool_id"))
success = temporary.UpdateString("account_key",app.StringOf("account_key"))
Dim temporarytemporaryAWScredentials As New Chilkat.FileAccess
success = temporarytemporaryAWScredentials.DirEnsureExists("qa_data/tokens")
If (success <> True) Then
    System.DebugLog("Could not create the private cache directory.")
    Return
End If

If (temporarytemporaryAWScredentials.FileExists("qa_data/tokens/cognito-identity.json") = True) Then
    success = temporarytemporaryAWScredentials.FileCopy("qa_data/tokens/cognito-identity.json","qa_data/tokens/cognito-identity.json.bak",False)
    If (success <> True) Then
        System.DebugLog("Could not back up the existing cache.")
        Return
    End If

End If

success = temporary.WriteFile("qa_data/tokens/cognito-identity.json")
If (success <> True) Then
    System.DebugLog("Could not save temporary AWS credentials; preserve any previous backup.")
    Return
End If

System.DebugLog("Identity ID: " + result.StringOf("IdentityId"))
System.DebugLog("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.