Amazon Cognito: Refresh Tokens with Rotation Support
See more Amazon Cognito Examples
Renew a user session without asking for the password again. Choose the default GetTokensFromRefreshToken JSON API or the OAuth refresh_token grant. Both support refresh-token rotation. REFRESH_TOKEN_AUTH is incompatible with rotation and is intentionally not used. With rotation disabled, retain the old refresh token when the response omits a replacement; with rotation enabled, save the new one before another refresh.
Use a public client without a secret, matching the initial sign-in. Managed-login sessions can use the OAuth endpoint. API-origin sessions can use OAuth refresh only when device remembering is disabled; otherwise use the API with the confirmed DeviceKey. This collection's password sign-in example assumes device remembering is disabled. Coordinate simultaneous refreshes and handle the configured retry grace period; expiration or revocation requires a new sign-in. Rotating does not extend the original refresh-token lifetime.
Uses direct Chilkat.Http requests to the regional Cognito User Pools JSON API. Public app-client operations do not use IAM signing. These examples use a public app client without a client secret; do not add administrative AWS credentials. For a confidential app client, implement the operation-specific SecretHash/SECRET_HASH or ClientSecret requirements on a trusted system.
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
Chilkat AutoIt Downloads
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
; "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
Local $sMethod = "api"
If (($sMethod <> "api") And ($sMethod <> "oauth")) Then
ConsoleWrite("Choose api or oauth." & @CRLF)
Exit
EndIf
$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("refresh_token") <> 1) Or ($oCached.StringOf("refresh_token") = "")) Then
ConsoleWrite("Missing or invalid refresh_token." & @CRLF)
Exit
EndIf
If ($sMethod = "api") Then
$oBody.UpdateString("ClientId",$sClientId)
$oBody.UpdateString("RefreshToken",$oCached.StringOf("refresh_token"))
; If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
If (($oCached.JsonTypeOf("device_key") = 1) And ($oCached.StringOf("device_key") <> "")) Then
$oBody.UpdateString("DeviceKey",$oCached.StringOf("device_key"))
EndIf
$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.GetTokensFromRefreshToken"
$bSuccess = $oHttp.HttpJson("POST",$oEndpoint.GetAsString(),$oBody,"application/x-amz-json-1.0",$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
Else
If (($oApp.JsonTypeOf("domain") <> 1) Or ($oApp.StringOf("domain") = "")) Then
ConsoleWrite("Missing or invalid domain." & @CRLF)
Exit
EndIf
; This URL comes from trusted configuration, never from a token or user-supplied URL.
$oTokenEndpoint = ObjCreate("Chilkat.StringBuilder")
$oTokenEndpoint.Append($oApp.StringOf("domain"))
$oTokenEndpoint.Append("/oauth2/token")
$oReq = ObjCreate("Chilkat.HttpRequest")
$oReq.HttpVerb = "POST"
$oReq.ContentType = "application/x-www-form-urlencoded"
$oReq.AddParam "grant_type","refresh_token"
$oReq.AddParam "client_id",$sClientId
$oReq.AddParam "refresh_token",$oCached.StringOf("refresh_token")
$bSuccess = $oHttp.HttpReq($oTokenEndpoint.GetAsString(),$oReq,$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
EndIf
$oToken = ObjCreate("Chilkat.JsonObject")
If ($sMethod = "api") Then
$oToken.UpdateString("access_token",$oResult.StringOf("AuthenticationResult.AccessToken"))
$oToken.UpdateString("id_token",$oResult.StringOf("AuthenticationResult.IdToken"))
$oToken.UpdateString("token_type",$oResult.StringOf("AuthenticationResult.TokenType"))
$oToken.UpdateInt("expires_in",$oResult.IntOf("AuthenticationResult.ExpiresIn"))
If ($oResult.HasMember("AuthenticationResult.RefreshToken") = True) Then
$oToken.UpdateString("refresh_token",$oResult.StringOf("AuthenticationResult.RefreshToken"))
EndIf
Else
$bSuccess = $oToken.Load($oResult.Emit())
If ($bSuccess <> True) Then
ConsoleWrite("Could not copy the token response." & @CRLF)
Exit
EndIf
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOf("access_token") = "")) Then
ConsoleWrite("Missing or invalid access_token." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("id_token") <> 1) Or ($oToken.StringOf("id_token") = "")) Then
ConsoleWrite("Missing or invalid id_token." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("expires_in") <> 2) Or ($oToken.IntOf("expires_in") <= 0)) Then
ConsoleWrite("Expected a positive token lifetime." & @CRLF)
Exit
EndIf
If ($oToken.StringOf("token_type") <> "Bearer") Then
ConsoleWrite("Expected Bearer tokens." & @CRLF)
Exit
EndIf
; Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
If ($oToken.HasMember("refresh_token") = True) Then
If (($oToken.JsonTypeOf("refresh_token") <> 1) Or ($oToken.StringOf("refresh_token") = "")) Then
ConsoleWrite("Missing or invalid refresh_token." & @CRLF)
Exit
EndIf
Else
$oToken.UpdateString("refresh_token",$oCached.StringOf("refresh_token"))
EndIf
If (($oCached.JsonTypeOf("device_key") = 1) And ($oCached.StringOf("device_key") <> "")) Then
$oToken.UpdateString("device_key",$oCached.StringOf("device_key"))
EndIf
$oToken.UpdateString("client_id",$oApp.StringOf("client_id"))
$oToken.UpdateString("user_pool_id",$oApp.StringOf("user_pool_id"))
$oToken.UpdateString("account_key",$oApp.StringOf("account_key"))
$oObtained = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oObtained.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not get the acquisition time." & @CRLF)
Exit
EndIf
$oToken.UpdateString("obtained_at",$oObtained.GetAsTimestamp(False))
$oTokenrefreshedusertokens = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oTokenrefreshedusertokens.DirEnsureExists("qa_data/tokens")
If ($bSuccess <> True) Then
ConsoleWrite("Could not create the private cache directory." & @CRLF)
Exit
EndIf
If ($oTokenrefreshedusertokens.FileExists("qa_data/tokens/cognito-user.json") = True) Then
$bSuccess = $oTokenrefreshedusertokens.FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",False)
If ($bSuccess <> True) Then
ConsoleWrite("Could not back up the existing cache." & @CRLF)
Exit
EndIf
EndIf
$bSuccess = $oToken.WriteFile("qa_data/tokens/cognito-user.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save refreshed user tokens; preserve any previous backup." & @CRLF)
Exit
EndIf
ConsoleWrite("Tokens refreshed; private cache updated." & @CRLF)