Sample code for 30+ languages & platforms
AutoIt Requires Chilkat v11.6.0+

Amazon Cognito: Enroll an Authenticator for TOTP MFA

See more Amazon Cognito Examples

Enable software-token MFA in the pool first. Choose mode=signed_in to enroll with a user access token containing aws.cognito.signin.user.admin, or mode=challenge to continue the MFA_SETUP saved by the sign-in example. Begin obtains a secret and saves it in private cognito-totp.json. Present secret_code securely to the user for manual entry or an otpauth QR code; never place it in ordinary logs. Then set action=verify with the authenticator's code in private totp-input.json.

Checks VerifySoftwareToken.Status=SUCCESS before activating the preference or finishing sign-in. A signed-in enrollment sets SoftwareTokenMfaSettings.Enabled and PreferredMfa. Challenge enrollment uses the successive Session values from AssociateSoftwareToken and VerifySoftwareToken, then RespondToAuthChallenge(MFA_SETUP). Verifying a replacement authenticator can disassociate the old one. If a later step fails after successful verification, inspect the user's MFA/sign-in state rather than repeatedly beginning enrollment.

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 | 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
Local $sAction = "begin"
Local $sMode = "signed_in"
If (($sAction <> "begin") And ($sAction <> "verify")) Then
    ConsoleWrite("Choose begin or verify." & @CRLF)
    Exit
EndIf

If (($sMode <> "signed_in") And ($sMode <> "challenge")) Then
    ConsoleWrite("Choose signed_in or challenge." & @CRLF)
    Exit
EndIf

Local $sUsername = ""
$oCredential = ObjCreate("Chilkat.JsonObject")
If ($sMode = "signed_in") Then
    $bSuccess = $oCredential.LoadFile("qa_data/tokens/cognito-user.json")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not load user tokens." & @CRLF)
        Exit
    EndIf

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

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

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

    If ($oCredential.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 (($oCredential.JsonTypeOf("account_key") <> 1) Or ($oCredential.StringOf("account_key") = "")) Then
        ConsoleWrite("Missing or invalid account_key." & @CRLF)
        Exit
    EndIf

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

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

Else
    $bSuccess = $oCredential.LoadFile("qa_data/tokens/cognito-challenge.json")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not load the MFA_SETUP challenge." & @CRLF)
        Exit
    EndIf

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

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

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

    If ($oCredential.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 (($oCredential.JsonTypeOf("account_key") <> 1) Or ($oCredential.StringOf("account_key") = "")) Then
        ConsoleWrite("Missing or invalid account_key." & @CRLF)
        Exit
    EndIf

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

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

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

    If ($oCredential.StringOf("ChallengeName") <> "MFA_SETUP") Then
        ConsoleWrite("Expected an MFA_SETUP challenge." & @CRLF)
        Exit
    EndIf

    $sUsername = $oCredential.StringOf("username")
EndIf

If ($sAction = "begin") Then
    If ($sMode = "signed_in") Then
        $oBody.UpdateString("AccessToken",$oCredential.StringOf("access_token"))
    Else
        $oBody.UpdateString("Session",$oCredential.StringOf("Session"))
    EndIf

    $oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.AssociateSoftwareToken"
    $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

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

    $oNewEnrollment = ObjCreate("Chilkat.JsonObject")
    $oNewEnrollment.UpdateString("secret_code",$oResult.StringOf("SecretCode"))
    $oNewEnrollment.UpdateString("mode",$sMode)
    $oNewEnrollment.UpdateString("username",$sUsername)
    If ($sMode = "challenge") Then
        If (($oResult.JsonTypeOf("Session") <> 1) Or ($oResult.StringOf("Session") = "")) Then
            ConsoleWrite("Missing or invalid Session." & @CRLF)
            Exit
        EndIf

        $oNewEnrollment.UpdateString("session",$oResult.StringOf("Session"))
        ;  Bind enrollment to this precise challenge, not just the account.
        $oNewEnrollment.UpdateString("original_session",$oCredential.StringOf("Session"))
    EndIf

    $oNewEnrollment.UpdateString("client_id",$oApp.StringOf("client_id"))
    $oNewEnrollment.UpdateString("user_pool_id",$oApp.StringOf("user_pool_id"))
    $oNewEnrollment.UpdateString("account_key",$oApp.StringOf("account_key"))
    $oNewEnrollmentTOTPenrollment = ObjCreate("Chilkat.FileAccess")
    $bSuccess = $oNewEnrollmentTOTPenrollment.DirEnsureExists("qa_data/tokens")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not create the private cache directory." & @CRLF)
        Exit
    EndIf

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

    EndIf

    $bSuccess = $oNewEnrollment.WriteFile("qa_data/tokens/cognito-totp.json")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not save TOTP enrollment; preserve any previous backup." & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Enrollment saved. Present secret_code privately in your authenticator setup UI." & @CRLF)
    ;  This secret can generate future OTPs. Never log it or email it.
    Exit
EndIf

$oEnrollment = ObjCreate("Chilkat.JsonObject")
$oEnrollment.Strict = True
$bSuccess = $oEnrollment.LoadFile("qa_data/tokens/cognito-totp.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load qa_data/tokens/cognito-totp.json." & @CRLF)
    Exit
EndIf

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

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

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

If ($oEnrollment.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 (($oEnrollment.JsonTypeOf("account_key") <> 1) Or ($oEnrollment.StringOf("account_key") = "")) Then
    ConsoleWrite("Missing or invalid account_key." & @CRLF)
    Exit
EndIf

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

If ($oEnrollment.StringOf("mode") <> $sMode) Then
    ConsoleWrite("Enrollment mode mismatch." & @CRLF)
    Exit
EndIf

$oInput = ObjCreate("Chilkat.JsonObject")
$oInput.Strict = True
$bSuccess = $oInput.LoadFile("qa_data/cognito/totp-input.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load qa_data/cognito/totp-input.json." & @CRLF)
    Exit
EndIf

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

;  Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
$oBody.UpdateString("UserCode",$oInput.StringOf("code"))
$oBody.UpdateString("FriendlyDeviceName","Authenticator")
If ($sMode = "signed_in") Then
    $oBody.UpdateString("AccessToken",$oCredential.StringOf("access_token"))
Else
    If (($oEnrollment.JsonTypeOf("session") <> 1) Or ($oEnrollment.StringOf("session") = "")) Then
        ConsoleWrite("Missing or invalid session." & @CRLF)
        Exit
    EndIf

    If ($oEnrollment.StringOf("original_session") <> $oCredential.StringOf("Session")) Then
        ConsoleWrite("Enrollment belongs to another sign-in challenge." & @CRLF)
        Exit
    EndIf

    $oBody.UpdateString("Session",$oEnrollment.StringOf("session"))
EndIf

$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.VerifySoftwareToken"
$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

If ($oResult.StringOf("Status") <> "SUCCESS") Then
    ConsoleWrite("Authenticator verification did not succeed; do not enable it." & @CRLF)
    Exit
EndIf

;  Verification succeeded. Discard the enrollment secret and its backup.
$oRemoveEnrollment = ObjCreate("Chilkat.FileAccess")
$oRemoveEnrollment.FileDelete("qa_data/tokens/cognito-totp.json")
If ($oRemoveEnrollment.FileExists("qa_data/tokens/cognito-totp.json.bak") = True) Then
    $oRemoveEnrollment.FileDelete("qa_data/tokens/cognito-totp.json.bak")
EndIf

$bSuccess = $oBody.Load("{}")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not reset the request body." & @CRLF)
    Exit
EndIf

If ($sMode = "signed_in") Then
    $oBody.UpdateString("AccessToken",$oCredential.StringOf("access_token"))
    $oBody.UpdateBool("SoftwareTokenMfaSettings.Enabled",True)
    $oBody.UpdateBool("SoftwareTokenMfaSettings.PreferredMfa",True)
    $oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.SetUserMFAPreference"
    $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

    ConsoleWrite("Authenticator verified and set as the preferred MFA method." & @CRLF)
    Exit
EndIf

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

;  Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
$oBody.UpdateString("ClientId",$sClientId)
$oBody.UpdateString("ChallengeName","MFA_SETUP")
$oBody.UpdateString("Session",$oResult.StringOf("Session"))
$oBody.UpdateString("ChallengeResponses.USERNAME",$sUsername)
$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.RespondToAuthChallenge"
$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

If ($oResult.JsonTypeOf("AuthenticationResult") = 3) Then
    $oToken = ObjCreate("Chilkat.JsonObject")
    $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

    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

    If (($oToken.JsonTypeOf("refresh_token") <> 1) Or ($oToken.StringOf("refresh_token") = "")) Then
        ConsoleWrite("Missing or invalid refresh_token." & @CRLF)
        Exit
    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))
    $oTokenusertokens = ObjCreate("Chilkat.FileAccess")
    $bSuccess = $oTokenusertokens.DirEnsureExists("qa_data/tokens")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not create the private cache directory." & @CRLF)
        Exit
    EndIf

    If ($oTokenusertokens.FileExists("qa_data/tokens/cognito-user.json") = True) Then
        $bSuccess = $oTokenusertokens.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 user tokens; preserve any previous backup." & @CRLF)
        Exit
    EndIf

    ;  A completed flow no longer needs its short-lived challenge session.
    $oCleanup = ObjCreate("Chilkat.FileAccess")
    If ($oCleanup.FileExists("qa_data/tokens/cognito-challenge.json") = True) Then
        $oCleanup.FileDelete("qa_data/tokens/cognito-challenge.json")
    EndIf

    ConsoleWrite("Sign-in completed; private token cache saved." & @CRLF)
    Exit
EndIf

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

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

;  ChallengeParameters may provide the canonical username after alias-based sign-in.
If (($oResult.JsonTypeOf("ChallengeParameters.USER_ID_FOR_SRP") = 1) And ($oResult.StringOf("ChallengeParameters.USER_ID_FOR_SRP") <> "")) Then
    $sUsername = $oResult.StringOf("ChallengeParameters.USER_ID_FOR_SRP")
EndIf

If (($oResult.JsonTypeOf("ChallengeParameters.USERNAME") = 1) And ($oResult.StringOf("ChallengeParameters.USERNAME") <> "")) Then
    $sUsername = $oResult.StringOf("ChallengeParameters.USERNAME")
EndIf

$oResult.UpdateString("username",$sUsername)
$oResult.UpdateString("client_id",$oApp.StringOf("client_id"))
$oResult.UpdateString("user_pool_id",$oApp.StringOf("user_pool_id"))
$oResult.UpdateString("account_key",$oApp.StringOf("account_key"))
$oResultauthenticationchallenge = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oResultauthenticationchallenge.DirEnsureExists("qa_data/tokens")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the private cache directory." & @CRLF)
    Exit
EndIf

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

EndIf

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

ConsoleWrite("Further authentication required: " & $oResult.StringOf("ChallengeName") & @CRLF)
;  Collect the requested input in your application's UI; never print the Session value.