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 Unicode C++ Downloads
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkJsonArrayW.h>
#include <CkDateTimeW.h>
#include <CkFileAccessW.h>
void ChilkatSample(void)
{
bool success = 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.
CkJsonObjectW app;
app.put_Strict(true);
success = app.LoadFile(L"qa_data/cognito/app.json");
if (success != true) {
wprintf(L"Could not load Cognito app settings.\n");
return;
}
if ((app.JsonTypeOf(L"region") != 1) || (app.stringOf(L"region") == L"")) {
wprintf(L"Missing or invalid region.\n");
return;
}
if ((app.JsonTypeOf(L"user_pool_id") != 1) || (app.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if ((app.JsonTypeOf(L"client_id") != 1) || (app.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if ((app.JsonTypeOf(L"account_key") != 1) || (app.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
const wchar_t *clientId = app.stringOf(L"client_id");
CkStringBuilderW endpoint;
endpoint.Append(L"https://cognito-idp.");
endpoint.Append(app.stringOf(L"region"));
endpoint.Append(L".amazonaws.com/");
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
CkHttpResponseW resp;
CkJsonObjectW body;
CkJsonObjectW result;
result.put_Strict(true);
// "start" begins sign-in. "respond" submits input for the most recent saved challenge.
const wchar_t *action = L"start";
if ((action != L"start") && (action != L"respond")) {
wprintf(L"Choose start or respond.\n");
return;
}
CkJsonObjectW input;
input.put_Strict(true);
success = input.LoadFile(L"qa_data/cognito/signin-input.json");
if (success != true) {
wprintf(L"Could not load qa_data/cognito/signin-input.json.\n");
return;
}
if ((input.JsonTypeOf(L"username") != 1) || (input.stringOf(L"username") == L"")) {
wprintf(L"Missing or invalid username.\n");
return;
}
const wchar_t *username = input.stringOf(L"username");
body.UpdateString(L"ClientId",clientId);
if (action == L"start") {
if ((input.JsonTypeOf(L"password") != 1) || (input.stringOf(L"password") == L"")) {
wprintf(L"Missing or invalid password.\n");
return;
}
body.UpdateString(L"AuthFlow",L"USER_PASSWORD_AUTH");
body.UpdateString(L"AuthParameters.USERNAME",username);
body.UpdateString(L"AuthParameters.PASSWORD",input.stringOf(L"password"));
http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.InitiateAuth");
success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
if (resp.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
success = result.Load(resp.bodyStr());
if (success == true) {
wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != true) {
wprintf(L"The HTTP exchange did not complete.\n");
return;
}
success = result.Load(resp.bodyStr());
if (success != true) {
wprintf(L"Expected a JSON response.\n");
return;
}
}
else {
CkJsonObjectW challenge;
challenge.put_Strict(true);
success = challenge.LoadFile(L"qa_data/tokens/cognito-challenge.json");
if (success != true) {
wprintf(L"Could not load qa_data/tokens/cognito-challenge.json.\n");
return;
}
if ((challenge.JsonTypeOf(L"client_id") != 1) || (challenge.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if (challenge.stringOf(L"client_id") != app.stringOf(L"client_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((challenge.JsonTypeOf(L"user_pool_id") != 1) || (challenge.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if (challenge.stringOf(L"user_pool_id") != app.stringOf(L"user_pool_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((challenge.JsonTypeOf(L"account_key") != 1) || (challenge.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
if (challenge.stringOf(L"account_key") != app.stringOf(L"account_key")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((challenge.JsonTypeOf(L"Session") != 1) || (challenge.stringOf(L"Session") == L"")) {
wprintf(L"Missing or invalid Session.\n");
return;
}
if ((challenge.JsonTypeOf(L"ChallengeName") != 1) || (challenge.stringOf(L"ChallengeName") == L"")) {
wprintf(L"Missing or invalid ChallengeName.\n");
return;
}
if ((challenge.JsonTypeOf(L"username") != 1) || (challenge.stringOf(L"username") == L"")) {
wprintf(L"Missing or invalid username.\n");
return;
}
// Use the bound canonical username from the previous response, not a new alias.
username = challenge.stringOf(L"username");
const wchar_t *challengeName = challenge.stringOf(L"ChallengeName");
body.UpdateString(L"Session",challenge.stringOf(L"Session"));
body.UpdateString(L"ChallengeName",challengeName);
body.UpdateString(L"ChallengeResponses.USERNAME",username);
if (challengeName == L"NEW_PASSWORD_REQUIRED") {
if ((input.JsonTypeOf(L"new_password") != 1) || (input.stringOf(L"new_password") == L"")) {
wprintf(L"Missing or invalid new_password.\n");
return;
}
body.UpdateString(L"ChallengeResponses.NEW_PASSWORD",input.stringOf(L"new_password"));
// requiredAttributes is a JSON array encoded inside a JSON string.
CkJsonArrayW requiredAttributes;
const wchar_t *requiredJson = challenge.stringOf(L"ChallengeParameters.requiredAttributes");
if (challenge.HasMember(L"ChallengeParameters.requiredAttributes") != true) {
requiredJson = L"[]";
}
success = requiredAttributes.Load(requiredJson);
if (success != true) {
wprintf(L"Invalid required-attributes list.\n");
return;
}
CkJsonObjectW answers;
success = body.ObjectOf2(L"ChallengeResponses",answers);
if (success != true) {
wprintf(L"Could not access challenge responses.\n");
return;
}
int i = 0;
int count = requiredAttributes.get_Size();
const wchar_t *attribute = 0;
const wchar_t *attributeValue = 0;
CkJsonObjectW supplied;
if (count > 0) {
success = input.ObjectOf2(L"required_attributes",supplied);
if (success != true) {
wprintf(L"Supply all required attributes in required_attributes.\n");
return;
}
}
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.
CkStringBuilderW attributePath;
attributePath.Append(L"\"");
attributePath.Append(attribute);
attributePath.Append(L"\"");
attributeValue = supplied.stringOf(attributePath.getAsString());
if ((supplied.JsonTypeOf(attributePath.getAsString()) != 1) || (attributeValue == L"")) {
wprintf(L"A required user attribute is missing.\n");
return;
}
answers.AppendString(attribute,attributeValue);
i = i + 1;
}
}
else {
if ((challengeName != L"SMS_MFA") && (challengeName != L"SOFTWARE_TOKEN_MFA") && (challengeName != L"EMAIL_OTP")) {
wprintf(L"This challenge needs a different handler: %s\n",challengeName);
// MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
return;
}
if ((input.JsonTypeOf(L"code") != 1) || (input.stringOf(L"code") == L"")) {
wprintf(L"Missing or invalid code.\n");
return;
}
if (challengeName == L"SMS_MFA") {
body.UpdateString(L"ChallengeResponses.SMS_MFA_CODE",input.stringOf(L"code"));
}
if (challengeName == L"SOFTWARE_TOKEN_MFA") {
body.UpdateString(L"ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE",input.stringOf(L"code"));
}
if (challengeName == L"EMAIL_OTP") {
body.UpdateString(L"ChallengeResponses.EMAIL_OTP_CODE",input.stringOf(L"code"));
}
}
http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.RespondToAuthChallenge");
success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
if (resp.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
success = result.Load(resp.bodyStr());
if (success == true) {
wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != true) {
wprintf(L"The HTTP exchange did not complete.\n");
return;
}
success = result.Load(resp.bodyStr());
if (success != true) {
wprintf(L"Expected a JSON response.\n");
return;
}
}
if (result.JsonTypeOf(L"AuthenticationResult") == 3) {
CkJsonObjectW token;
token.UpdateString(L"access_token",result.stringOf(L"AuthenticationResult.AccessToken"));
token.UpdateString(L"id_token",result.stringOf(L"AuthenticationResult.IdToken"));
token.UpdateString(L"token_type",result.stringOf(L"AuthenticationResult.TokenType"));
token.UpdateInt(L"expires_in",result.IntOf(L"AuthenticationResult.ExpiresIn"));
if (result.HasMember(L"AuthenticationResult.RefreshToken") == true) {
token.UpdateString(L"refresh_token",result.stringOf(L"AuthenticationResult.RefreshToken"));
}
if ((token.JsonTypeOf(L"access_token") != 1) || (token.stringOf(L"access_token") == L"")) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
if ((token.JsonTypeOf(L"id_token") != 1) || (token.stringOf(L"id_token") == L"")) {
wprintf(L"Missing or invalid id_token.\n");
return;
}
if ((token.JsonTypeOf(L"expires_in") != 2) || (token.IntOf(L"expires_in") <= 0)) {
wprintf(L"Expected a positive token lifetime.\n");
return;
}
if (token.stringOf(L"token_type") != L"Bearer") {
wprintf(L"Expected Bearer tokens.\n");
return;
}
if ((token.JsonTypeOf(L"refresh_token") != 1) || (token.stringOf(L"refresh_token") == L"")) {
wprintf(L"Missing or invalid refresh_token.\n");
return;
}
token.UpdateString(L"client_id",app.stringOf(L"client_id"));
token.UpdateString(L"user_pool_id",app.stringOf(L"user_pool_id"));
token.UpdateString(L"account_key",app.stringOf(L"account_key"));
CkDateTimeW obtained;
success = obtained.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not get the acquisition time.\n");
return;
}
token.UpdateString(L"obtained_at",obtained.getAsTimestamp(false));
CkFileAccessW tokenusertokens;
success = tokenusertokens.DirEnsureExists(L"qa_data/tokens");
if (success != true) {
wprintf(L"Could not create the private cache directory.\n");
return;
}
if (tokenusertokens.FileExists(L"qa_data/tokens/cognito-user.json") == true) {
success = tokenusertokens.FileCopy(L"qa_data/tokens/cognito-user.json",L"qa_data/tokens/cognito-user.json.bak",false);
if (success != true) {
wprintf(L"Could not back up the existing cache.\n");
return;
}
}
success = token.WriteFile(L"qa_data/tokens/cognito-user.json");
if (success != true) {
wprintf(L"Could not save user tokens; preserve any previous backup.\n");
return;
}
// A completed flow no longer needs its short-lived challenge session.
CkFileAccessW cleanup;
if (cleanup.FileExists(L"qa_data/tokens/cognito-challenge.json") == true) {
cleanup.FileDelete(L"qa_data/tokens/cognito-challenge.json");
}
wprintf(L"Sign-in completed; private token cache saved.\n");
return;
}
if ((result.JsonTypeOf(L"ChallengeName") != 1) || (result.stringOf(L"ChallengeName") == L"")) {
wprintf(L"Missing or invalid ChallengeName.\n");
return;
}
if ((result.JsonTypeOf(L"Session") != 1) || (result.stringOf(L"Session") == L"")) {
wprintf(L"Missing or invalid Session.\n");
return;
}
// ChallengeParameters may provide the canonical username after alias-based sign-in.
if ((result.JsonTypeOf(L"ChallengeParameters.USER_ID_FOR_SRP") == 1) && (result.stringOf(L"ChallengeParameters.USER_ID_FOR_SRP") != L"")) {
username = result.stringOf(L"ChallengeParameters.USER_ID_FOR_SRP");
}
if ((result.JsonTypeOf(L"ChallengeParameters.USERNAME") == 1) && (result.stringOf(L"ChallengeParameters.USERNAME") != L"")) {
username = result.stringOf(L"ChallengeParameters.USERNAME");
}
result.UpdateString(L"username",username);
result.UpdateString(L"client_id",app.stringOf(L"client_id"));
result.UpdateString(L"user_pool_id",app.stringOf(L"user_pool_id"));
result.UpdateString(L"account_key",app.stringOf(L"account_key"));
CkFileAccessW resultauthenticationchallenge;
success = resultauthenticationchallenge.DirEnsureExists(L"qa_data/tokens");
if (success != true) {
wprintf(L"Could not create the private cache directory.\n");
return;
}
if (resultauthenticationchallenge.FileExists(L"qa_data/tokens/cognito-challenge.json") == true) {
success = resultauthenticationchallenge.FileCopy(L"qa_data/tokens/cognito-challenge.json",L"qa_data/tokens/cognito-challenge.json.bak",false);
if (success != true) {
wprintf(L"Could not back up the existing cache.\n");
return;
}
}
success = result.WriteFile(L"qa_data/tokens/cognito-challenge.json");
if (success != true) {
wprintf(L"Could not save authentication challenge; preserve any previous backup.\n");
return;
}
wprintf(L"Further authentication required: %s\n",result.stringOf(L"ChallengeName"));
// Collect the requested input in your application's UI; never print the Session value.
}