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 B4X 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 ChilkatJsonObject
app.Initialize
app.Strict = True
success = app.LoadFile("qa_data/cognito/app.json")
If success <> True Then
Log("Could not load Cognito app settings.")
Return
End If
If (app.JsonTypeOf("region") <> 1) Or (app.StringOf("region") = "") Then
Log("Missing or invalid region.")
Return
End If
If (app.JsonTypeOf("user_pool_id") <> 1) Or (app.StringOf("user_pool_id") = "") Then
Log("Missing or invalid user_pool_id.")
Return
End If
If (app.JsonTypeOf("client_id") <> 1) Or (app.StringOf("client_id") = "") Then
Log("Missing or invalid client_id.")
Return
End If
If (app.JsonTypeOf("account_key") <> 1) Or (app.StringOf("account_key") = "") Then
Log("Missing or invalid account_key.")
Return
End If
Dim clientId As String = app.StringOf("client_id")
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.StringOf("region"))
endpoint.Append(".amazonaws.com/")
Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim body As ChilkatJsonObject
body.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
' "start" begins sign-in. "respond" submits input for the most recent saved challenge.
Dim action As String = "start"
If (action <> "start") And (action <> "respond") Then
Log("Choose start or respond.")
Return
End If
Dim input As ChilkatJsonObject
input.Initialize
input.Strict = True
success = input.LoadFile("qa_data/cognito/signin-input.json")
If success <> True Then
Log("Could not load qa_data/cognito/signin-input.json.")
Return
End If
If (input.JsonTypeOf("username") <> 1) Or (input.StringOf("username") = "") Then
Log("Missing or invalid username.")
Return
End If
Dim username As String = input.StringOf("username")
body.UpdateString("ClientId", clientId)
If action = "start" Then
If (input.JsonTypeOf("password") <> 1) Or (input.StringOf("password") = "") Then
Log("Missing or invalid password.")
Return
End If
body.UpdateString("AuthFlow", "USER_PASSWORD_AUTH")
body.UpdateString("AuthParameters.USERNAME", username)
body.UpdateString("AuthParameters.PASSWORD", input.StringOf("password"))
http.SetRequestHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth")
success = http.HttpJson("POST", endpoint.GetAsString, body, "application/x-amz-json-1.0", resp)
If resp.StatusCode <> 200 Then
Log("HTTP status: " & resp.StatusCode)
success = result.Load(resp.BodyStr)
If success = True Then
Log("Error type: " & result.StringOf("__type"))
Log("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
Log("The HTTP exchange did not complete.")
Return
End If
success = result.Load(resp.BodyStr)
If success <> True Then
Log("Expected a JSON response.")
Return
End If
Else
Dim challenge As ChilkatJsonObject
challenge.Initialize
challenge.Strict = True
success = challenge.LoadFile("qa_data/tokens/cognito-challenge.json")
If success <> True Then
Log("Could not load qa_data/tokens/cognito-challenge.json.")
Return
End If
If (challenge.JsonTypeOf("client_id") <> 1) Or (challenge.StringOf("client_id") = "") Then
Log("Missing or invalid client_id.")
Return
End If
If challenge.StringOf("client_id") <> app.StringOf("client_id") Then
Log("Saved data belongs to another client, pool, or local account.")
Return
End If
If (challenge.JsonTypeOf("user_pool_id") <> 1) Or (challenge.StringOf("user_pool_id") = "") Then
Log("Missing or invalid user_pool_id.")
Return
End If
If challenge.StringOf("user_pool_id") <> app.StringOf("user_pool_id") Then
Log("Saved data belongs to another client, pool, or local account.")
Return
End If
If (challenge.JsonTypeOf("account_key") <> 1) Or (challenge.StringOf("account_key") = "") Then
Log("Missing or invalid account_key.")
Return
End If
If challenge.StringOf("account_key") <> app.StringOf("account_key") Then
Log("Saved data belongs to another client, pool, or local account.")
Return
End If
If (challenge.JsonTypeOf("Session") <> 1) Or (challenge.StringOf("Session") = "") Then
Log("Missing or invalid Session.")
Return
End If
If (challenge.JsonTypeOf("ChallengeName") <> 1) Or (challenge.StringOf("ChallengeName") = "") Then
Log("Missing or invalid ChallengeName.")
Return
End If
If (challenge.JsonTypeOf("username") <> 1) Or (challenge.StringOf("username") = "") Then
Log("Missing or invalid username.")
Return
End If
' Use the bound canonical username from the previous response, not a new alias.
username = challenge.StringOf("username")
Dim challengeName As String = challenge.StringOf("ChallengeName")
body.UpdateString("Session", challenge.StringOf("Session"))
body.UpdateString("ChallengeName", challengeName)
body.UpdateString("ChallengeResponses.USERNAME", username)
If challengeName = "NEW_PASSWORD_REQUIRED" Then
If (input.JsonTypeOf("new_password") <> 1) Or (input.StringOf("new_password") = "") Then
Log("Missing or invalid new_password.")
Return
End If
body.UpdateString("ChallengeResponses.NEW_PASSWORD", input.StringOf("new_password"))
' requiredAttributes is a JSON array encoded inside a JSON string.
Dim requiredAttributes As ChilkatJsonArray
requiredAttributes.Initialize
Dim requiredJson As String = challenge.StringOf("ChallengeParameters.requiredAttributes")
If challenge.HasMember("ChallengeParameters.requiredAttributes") <> True Then
requiredJson = "[]"
End If
success = requiredAttributes.Load(requiredJson)
If success <> True Then
Log("Invalid required-attributes list.")
Return
End If
Dim answers As ChilkatJsonObject
answers.Initialize
success = body.ObjectOf2("ChallengeResponses", answers)
If success <> True Then
Log("Could not access challenge responses.")
Return
End If
Dim i As Int = 0
Dim count As Int = requiredAttributes.Size
Dim attribute As String
Dim attributeValue As String
Dim supplied As ChilkatJsonObject
supplied.Initialize
If count > 0 Then
success = input.ObjectOf2("required_attributes", supplied)
If success <> True Then
Log("Supply all required attributes in required_attributes.")
Return
End If
End If
Do While i < count
attribute = requiredAttributes.StringAt(i)
' Keys are returned as userAttributes.email, userAttributes.name, etc.
' StringOf with a quoted path treats the whole key literally.
Dim attributePath As ChilkatStringBuilder
attributePath.Initialize
attributePath.Append(Chr(34))
attributePath.Append(attribute)
attributePath.Append(Chr(34))
attributeValue = supplied.StringOf(attributePath.GetAsString)
If (supplied.JsonTypeOf(attributePath.GetAsString) <> 1) Or (attributeValue = "") Then
Log("A required user attribute is missing.")
Return
End If
answers.AppendString(attribute, attributeValue)
i = i + 1
Loop
Else
If (challengeName <> "SMS_MFA") And (challengeName <> "SOFTWARE_TOKEN_MFA") And (challengeName <> "EMAIL_OTP") Then
Log("This challenge needs a different handler: " & challengeName)
' MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
Return
End If
If (input.JsonTypeOf("code") <> 1) Or (input.StringOf("code") = "") Then
Log("Missing or invalid code.")
Return
End If
If challengeName = "SMS_MFA" Then
body.UpdateString("ChallengeResponses.SMS_MFA_CODE", input.StringOf("code"))
End If
If challengeName = "SOFTWARE_TOKEN_MFA" Then
body.UpdateString("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE", input.StringOf("code"))
End If
If challengeName = "EMAIL_OTP" Then
body.UpdateString("ChallengeResponses.EMAIL_OTP_CODE", input.StringOf("code"))
End If
End If
http.SetRequestHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.RespondToAuthChallenge")
success = http.HttpJson("POST", endpoint.GetAsString, body, "application/x-amz-json-1.0", resp)
If resp.StatusCode <> 200 Then
Log("HTTP status: " & resp.StatusCode)
success = result.Load(resp.BodyStr)
If success = True Then
Log("Error type: " & result.StringOf("__type"))
Log("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
Log("The HTTP exchange did not complete.")
Return
End If
success = result.Load(resp.BodyStr)
If success <> True Then
Log("Expected a JSON response.")
Return
End If
End If
If result.JsonTypeOf("AuthenticationResult") = 3 Then
Dim token As ChilkatJsonObject
token.Initialize
token.UpdateString("access_token", result.StringOf("AuthenticationResult.AccessToken"))
token.UpdateString("id_token", result.StringOf("AuthenticationResult.IdToken"))
token.UpdateString("token_type", result.StringOf("AuthenticationResult.TokenType"))
token.UpdateInt("expires_in", result.IntOf("AuthenticationResult.ExpiresIn"))
If result.HasMember("AuthenticationResult.RefreshToken") = True Then
token.UpdateString("refresh_token", result.StringOf("AuthenticationResult.RefreshToken"))
End If
If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOf("access_token") = "") Then
Log("Missing or invalid access_token.")
Return
End If
If (token.JsonTypeOf("id_token") <> 1) Or (token.StringOf("id_token") = "") Then
Log("Missing or invalid id_token.")
Return
End If
If (token.JsonTypeOf("expires_in") <> 2) Or (token.IntOf("expires_in") <= 0) Then
Log("Expected a positive token lifetime.")
Return
End If
If token.StringOf("token_type") <> "Bearer" Then
Log("Expected Bearer tokens.")
Return
End If
If (token.JsonTypeOf("refresh_token") <> 1) Or (token.StringOf("refresh_token") = "") Then
Log("Missing or invalid refresh_token.")
Return
End If
token.UpdateString("client_id", app.StringOf("client_id"))
token.UpdateString("user_pool_id", app.StringOf("user_pool_id"))
token.UpdateString("account_key", app.StringOf("account_key"))
Dim obtained As ChilkatDateTime
obtained.Initialize
success = obtained.SetFromCurrentSystemTime
If success <> True Then
Log("Could not get the acquisition time.")
Return
End If
token.UpdateString("obtained_at", obtained.GetAsTimestamp(False))
Dim tokenusertokens As ChilkatFileAccess
tokenusertokens.Initialize
success = tokenusertokens.DirEnsureExists("qa_data/tokens")
If success <> True Then
Log("Could not create the private cache directory.")
Return
End If
If tokenusertokens.FileExists("qa_data/tokens/cognito-user.json") = True Then
success = tokenusertokens.FileCopy("qa_data/tokens/cognito-user.json", "qa_data/tokens/cognito-user.json.bak", False)
If success <> True Then
Log("Could not back up the existing cache.")
Return
End If
End If
success = token.WriteFile("qa_data/tokens/cognito-user.json")
If success <> True Then
Log("Could not save user tokens; preserve any previous backup.")
Return
End If
' A completed flow no longer needs its short-lived challenge session.
Dim cleanup As ChilkatFileAccess
cleanup.Initialize
If cleanup.FileExists("qa_data/tokens/cognito-challenge.json") = True Then
cleanup.FileDelete("qa_data/tokens/cognito-challenge.json")
End If
Log("Sign-in completed; private token cache saved.")
Return
End If
If (result.JsonTypeOf("ChallengeName") <> 1) Or (result.StringOf("ChallengeName") = "") Then
Log("Missing or invalid ChallengeName.")
Return
End If
If (result.JsonTypeOf("Session") <> 1) Or (result.StringOf("Session") = "") Then
Log("Missing or invalid Session.")
Return
End If
' ChallengeParameters may provide the canonical username after alias-based sign-in.
If (result.JsonTypeOf("ChallengeParameters.USER_ID_FOR_SRP") = 1) And (result.StringOf("ChallengeParameters.USER_ID_FOR_SRP") <> "") Then
username = result.StringOf("ChallengeParameters.USER_ID_FOR_SRP")
End If
If (result.JsonTypeOf("ChallengeParameters.USERNAME") = 1) And (result.StringOf("ChallengeParameters.USERNAME") <> "") Then
username = result.StringOf("ChallengeParameters.USERNAME")
End If
result.UpdateString("username", username)
result.UpdateString("client_id", app.StringOf("client_id"))
result.UpdateString("user_pool_id", app.StringOf("user_pool_id"))
result.UpdateString("account_key", app.StringOf("account_key"))
Dim resultauthenticationchallenge As ChilkatFileAccess
resultauthenticationchallenge.Initialize
success = resultauthenticationchallenge.DirEnsureExists("qa_data/tokens")
If success <> True Then
Log("Could not create the private cache directory.")
Return
End If
If resultauthenticationchallenge.FileExists("qa_data/tokens/cognito-challenge.json") = True Then
success = resultauthenticationchallenge.FileCopy("qa_data/tokens/cognito-challenge.json", "qa_data/tokens/cognito-challenge.json.bak", False)
If success <> True Then
Log("Could not back up the existing cache.")
Return
End If
End If
success = result.WriteFile("qa_data/tokens/cognito-challenge.json")
If success <> True Then
Log("Could not save authentication challenge; preserve any previous backup.")
Return
End If
Log("Further authentication required: " & result.StringOf("ChallengeName"))
' Collect the requested input in your application's UI; never print the Session value.