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 VB.NET Downloads
Dim success As Boolean = 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
Debug.WriteLine("Could not load Cognito app settings.")
Exit Sub
End If
If ((app.JsonTypeOf("region") <> 1) Or (app.StringOf("region") = "")) Then
Debug.WriteLine("Missing or invalid region.")
Exit Sub
End If
If ((app.JsonTypeOf("user_pool_id") <> 1) Or (app.StringOf("user_pool_id") = "")) Then
Debug.WriteLine("Missing or invalid user_pool_id.")
Exit Sub
End If
If ((app.JsonTypeOf("client_id") <> 1) Or (app.StringOf("client_id") = "")) Then
Debug.WriteLine("Missing or invalid client_id.")
Exit Sub
End If
If ((app.JsonTypeOf("account_key") <> 1) Or (app.StringOf("account_key") = "")) Then
Debug.WriteLine("Missing or invalid account_key.")
Exit Sub
End If
Dim clientId As String = app.StringOf("client_id")
Dim endpoint As New Chilkat.StringBuilder
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.StringOf("region"))
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
Debug.WriteLine("Could not load qa_data/tokens/cognito-user.json.")
Exit Sub
End If
If ((cached.JsonTypeOf("client_id") <> 1) Or (cached.StringOf("client_id") = "")) Then
Debug.WriteLine("Missing or invalid client_id.")
Exit Sub
End If
If (cached.StringOf("client_id") <> app.StringOf("client_id")) Then
Debug.WriteLine("Saved data belongs to another client, pool, or local account.")
Exit Sub
End If
If ((cached.JsonTypeOf("user_pool_id") <> 1) Or (cached.StringOf("user_pool_id") = "")) Then
Debug.WriteLine("Missing or invalid user_pool_id.")
Exit Sub
End If
If (cached.StringOf("user_pool_id") <> app.StringOf("user_pool_id")) Then
Debug.WriteLine("Saved data belongs to another client, pool, or local account.")
Exit Sub
End If
If ((cached.JsonTypeOf("account_key") <> 1) Or (cached.StringOf("account_key") = "")) Then
Debug.WriteLine("Missing or invalid account_key.")
Exit Sub
End If
If (cached.StringOf("account_key") <> app.StringOf("account_key")) Then
Debug.WriteLine("Saved data belongs to another client, pool, or local account.")
Exit Sub
End If
If ((cached.JsonTypeOf("id_token") <> 1) Or (cached.StringOf("id_token") = "")) Then
Debug.WriteLine("Missing or invalid id_token.")
Exit Sub
End If
' Identity Pool region may differ from the User Pool region.
Dim identityRegion As String = "us-west-2"
Dim identityPoolId As String = "us-west-2:11111111-2222-3333-4444-555555555555"
Dim identityEndpoint As New Chilkat.StringBuilder
identityEndpoint.Append("https://cognito-identity.")
identityEndpoint.Append(identityRegion)
identityEndpoint.Append(".amazonaws.com/")
Dim provider As New Chilkat.StringBuilder
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")
Dim logins As New Chilkat.JsonObject
success = body.ObjectOf2("Logins",logins)
If (success <> True) Then
Debug.WriteLine("Could not create the Logins map.")
Exit Sub
End If
' 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.StatusCode <> 200) Then
Debug.WriteLine("HTTP status: " & resp.StatusCode)
success = result.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine("Error type: " & result.StringOf("__type"))
Debug.WriteLine("OAuth error: " & result.StringOf("error"))
End If
' Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
Exit Sub
End If
If (success <> True) Then
Debug.WriteLine("The HTTP exchange did not complete.")
Exit Sub
End If
success = result.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a JSON response.")
Exit Sub
End If
If ((result.JsonTypeOf("IdentityId") <> 1) Or (result.StringOf("IdentityId") = "")) Then
Debug.WriteLine("Missing or invalid IdentityId.")
Exit Sub
End If
Dim identityId As String = 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.StatusCode <> 200) Then
Debug.WriteLine("HTTP status: " & resp.StatusCode)
success = result.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine("Error type: " & result.StringOf("__type"))
Debug.WriteLine("OAuth error: " & result.StringOf("error"))
End If
' Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
Exit Sub
End If
If (success <> True) Then
Debug.WriteLine("The HTTP exchange did not complete.")
Exit Sub
End If
success = result.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a JSON response.")
Exit Sub
End If
If ((result.JsonTypeOf("IdentityId") <> 1) Or (result.StringOf("IdentityId") = "")) Then
Debug.WriteLine("Missing or invalid IdentityId.")
Exit Sub
End If
If ((result.JsonTypeOf("Credentials.AccessKeyId") <> 1) Or (result.StringOf("Credentials.AccessKeyId") = "")) Then
Debug.WriteLine("Missing or invalid Credentials.AccessKeyId.")
Exit Sub
End If
If ((result.JsonTypeOf("Credentials.SecretKey") <> 1) Or (result.StringOf("Credentials.SecretKey") = "")) Then
Debug.WriteLine("Missing or invalid Credentials.SecretKey.")
Exit Sub
End If
If ((result.JsonTypeOf("Credentials.SessionToken") <> 1) Or (result.StringOf("Credentials.SessionToken") = "")) Then
Debug.WriteLine("Missing or invalid Credentials.SessionToken.")
Exit Sub
End If
If (result.JsonTypeOf("Credentials.Expiration") <> 2) Then
Debug.WriteLine("Missing credential expiration.")
Exit Sub
End If
Dim temporary As New Chilkat.JsonObject
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"))
Dim temporarytemporaryAWScredentials As New Chilkat.FileAccess
success = temporarytemporaryAWScredentials.DirEnsureExists("qa_data/tokens")
If (success <> True) Then
Debug.WriteLine("Could not create the private cache directory.")
Exit Sub
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
Debug.WriteLine("Could not back up the existing cache.")
Exit Sub
End If
End If
success = temporary.WriteFile("qa_data/tokens/cognito-identity.json")
If (success <> True) Then
Debug.WriteLine("Could not save temporary AWS credentials; preserve any previous backup.")
Exit Sub
End If
Debug.WriteLine("Identity ID: " & result.StringOf("IdentityId"))
Debug.WriteLine("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.