Amazon Cognito: Sign In and Respond to Password or MFA Challenges
See more Amazon Cognito Examples
Enable ALLOW_USER_PASSWORD_AUTH on a public app client without a secret; use a password-based pool with device remembering disabled. Managed login with PKCE is preferable when your application need not handle passwords. This example illustrates the JSON API directly: start with username/password, then respond to each returned challenge with its latest Session. It does not implement SRP, remembered-device authentication, passkeys, custom challenges, or every possible challenge.
Set action=start with a private signin-input.json containing username and password. For respond, supply username plus new_password or code. NEW_PASSWORD_REQUIRED can also require a required_attributes object keyed by the names in ChallengeParameters.requiredAttributes, for example "userAttributes.email". Supply only requested missing attributes; existing required attributes cannot be changed during this challenge. Handles NEW_PASSWORD_REQUIRED, SMS_MFA, SOFTWARE_TOKEN_MFA and EMAIL_OTP. MFA_SETUP is handed to TOTP enrollment. Other challenges stop explicitly.
The latest challenge is saved privately with the canonical username and app/account binding. Only AuthenticationResult constitutes completed sign-in; a Session is not an access token. Confirmation codes remain strings, preserving leading zeroes. On timeout/expired session start again; do not reuse a session across users or parallel flows.
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
; "start" begins sign-in. "respond" submits input for the most recent saved challenge.
Local $sAction = "start"
If (($sAction <> "start") And ($sAction <> "respond")) Then
ConsoleWrite("Choose start or respond." & @CRLF)
Exit
EndIf
$oInput = ObjCreate("Chilkat.JsonObject")
$oInput.Strict = True
$bSuccess = $oInput.LoadFile("qa_data/cognito/signin-input.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load qa_data/cognito/signin-input.json." & @CRLF)
Exit
EndIf
If (($oInput.JsonTypeOf("username") <> 1) Or ($oInput.StringOf("username") = "")) Then
ConsoleWrite("Missing or invalid username." & @CRLF)
Exit
EndIf
Local $sUsername = $oInput.StringOf("username")
$oBody.UpdateString("ClientId",$sClientId)
If ($sAction = "start") Then
If (($oInput.JsonTypeOf("password") <> 1) Or ($oInput.StringOf("password") = "")) Then
ConsoleWrite("Missing or invalid password." & @CRLF)
Exit
EndIf
$oBody.UpdateString("AuthFlow","USER_PASSWORD_AUTH")
$oBody.UpdateString("AuthParameters.USERNAME",$sUsername)
$oBody.UpdateString("AuthParameters.PASSWORD",$oInput.StringOf("password"))
$oHttp.SetRequestHeader "X-Amz-Target","AWSCognitoIdentityProviderService.InitiateAuth"
$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
$oChallenge = ObjCreate("Chilkat.JsonObject")
$oChallenge.Strict = True
$bSuccess = $oChallenge.LoadFile("qa_data/tokens/cognito-challenge.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load qa_data/tokens/cognito-challenge.json." & @CRLF)
Exit
EndIf
If (($oChallenge.JsonTypeOf("client_id") <> 1) Or ($oChallenge.StringOf("client_id") = "")) Then
ConsoleWrite("Missing or invalid client_id." & @CRLF)
Exit
EndIf
If ($oChallenge.StringOf("client_id") <> $oApp.StringOf("client_id")) Then
ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
Exit
EndIf
If (($oChallenge.JsonTypeOf("user_pool_id") <> 1) Or ($oChallenge.StringOf("user_pool_id") = "")) Then
ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
Exit
EndIf
If ($oChallenge.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 (($oChallenge.JsonTypeOf("account_key") <> 1) Or ($oChallenge.StringOf("account_key") = "")) Then
ConsoleWrite("Missing or invalid account_key." & @CRLF)
Exit
EndIf
If ($oChallenge.StringOf("account_key") <> $oApp.StringOf("account_key")) Then
ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
Exit
EndIf
If (($oChallenge.JsonTypeOf("Session") <> 1) Or ($oChallenge.StringOf("Session") = "")) Then
ConsoleWrite("Missing or invalid Session." & @CRLF)
Exit
EndIf
If (($oChallenge.JsonTypeOf("ChallengeName") <> 1) Or ($oChallenge.StringOf("ChallengeName") = "")) Then
ConsoleWrite("Missing or invalid ChallengeName." & @CRLF)
Exit
EndIf
If (($oChallenge.JsonTypeOf("username") <> 1) Or ($oChallenge.StringOf("username") = "")) Then
ConsoleWrite("Missing or invalid username." & @CRLF)
Exit
EndIf
; Use the bound canonical username from the previous response, not a new alias.
$sUsername = $oChallenge.StringOf("username")
Local $sChallengeName = $oChallenge.StringOf("ChallengeName")
$oBody.UpdateString("Session",$oChallenge.StringOf("Session"))
$oBody.UpdateString("ChallengeName",$sChallengeName)
$oBody.UpdateString("ChallengeResponses.USERNAME",$sUsername)
If ($sChallengeName = "NEW_PASSWORD_REQUIRED") Then
If (($oInput.JsonTypeOf("new_password") <> 1) Or ($oInput.StringOf("new_password") = "")) Then
ConsoleWrite("Missing or invalid new_password." & @CRLF)
Exit
EndIf
$oBody.UpdateString("ChallengeResponses.NEW_PASSWORD",$oInput.StringOf("new_password"))
; requiredAttributes is a JSON array encoded inside a JSON string.
$oRequiredAttributes = ObjCreate("Chilkat.JsonArray")
Local $sRequiredJson = $oChallenge.StringOf("ChallengeParameters.requiredAttributes")
If ($oChallenge.HasMember("ChallengeParameters.requiredAttributes") <> True) Then
$sRequiredJson = "[]"
EndIf
$bSuccess = $oRequiredAttributes.Load($sRequiredJson)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid required-attributes list." & @CRLF)
Exit
EndIf
$oAnswers = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oBody.ObjectOf2("ChallengeResponses",$oAnswers)
If ($bSuccess <> True) Then
ConsoleWrite("Could not access challenge responses." & @CRLF)
Exit
EndIf
Local $i = 0
Local $iCount = $oRequiredAttributes.Size
Local $sAttribute
Local $sAttributeValue
$oSupplied = ObjCreate("Chilkat.JsonObject")
If ($iCount > 0) Then
$bSuccess = $oInput.ObjectOf2("required_attributes",$oSupplied)
If ($bSuccess <> True) Then
ConsoleWrite("Supply all required attributes in required_attributes." & @CRLF)
Exit
EndIf
EndIf
While $i < $iCount
$sAttribute = $oRequiredAttributes.StringAt($i)
; Keys are returned as userAttributes.email, userAttributes.name, etc.
; StringOf with a quoted path treats the whole key literally.
$oAttributePath = ObjCreate("Chilkat.StringBuilder")
$oAttributePath.Append("""")
$oAttributePath.Append($sAttribute)
$oAttributePath.Append("""")
$sAttributeValue = $oSupplied.StringOf($oAttributePath.GetAsString())
If (($oSupplied.JsonTypeOf($oAttributePath.GetAsString()) <> 1) Or ($sAttributeValue = "")) Then
ConsoleWrite("A required user attribute is missing." & @CRLF)
Exit
EndIf
$oAnswers.AppendString($sAttribute,$sAttributeValue)
$i = $i + 1
Wend
Else
If (($sChallengeName <> "SMS_MFA") And ($sChallengeName <> "SOFTWARE_TOKEN_MFA") And ($sChallengeName <> "EMAIL_OTP")) Then
ConsoleWrite("This challenge needs a different handler: " & $sChallengeName & @CRLF)
; MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
Exit
EndIf
If (($oInput.JsonTypeOf("code") <> 1) Or ($oInput.StringOf("code") = "")) Then
ConsoleWrite("Missing or invalid code." & @CRLF)
Exit
EndIf
If ($sChallengeName = "SMS_MFA") Then
$oBody.UpdateString("ChallengeResponses.SMS_MFA_CODE",$oInput.StringOf("code"))
EndIf
If ($sChallengeName = "SOFTWARE_TOKEN_MFA") Then
$oBody.UpdateString("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE",$oInput.StringOf("code"))
EndIf
If ($sChallengeName = "EMAIL_OTP") Then
$oBody.UpdateString("ChallengeResponses.EMAIL_OTP_CODE",$oInput.StringOf("code"))
EndIf
EndIf
$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
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.