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

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 CkPerl Downloads

CkPerl
use chilkat();

$success = 0;

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
#  App settings are trusted configuration. Keep a separate account_key/cache per local user.
$app = chilkat::CkJsonObject->new();
$app->put_Strict(1);
$success = $app->LoadFile("qa_data/cognito/app.json");
if ($success != 1) {
    print "Could not load Cognito app settings." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("region") != 1) or ($app->stringOf("region") == "")) {
    print "Missing or invalid region." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("user_pool_id") != 1) or ($app->stringOf("user_pool_id") == "")) {
    print "Missing or invalid user_pool_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("client_id") != 1) or ($app->stringOf("client_id") == "")) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("account_key") != 1) or ($app->stringOf("account_key") == "")) {
    print "Missing or invalid account_key." . "\r\n";
    exit;
}

$clientId = $app->stringOf("client_id");
$endpoint = chilkat::CkStringBuilder->new();
$endpoint->Append("https://cognito-idp.");
$endpoint->Append($app->stringOf("region"));
$endpoint->Append(".amazonaws.com/");
$http = chilkat::CkHttp->new();
$http->put_RequireSslCertVerify(1);
$http->put_FollowRedirects(0);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(60);
$resp = chilkat::CkHttpResponse->new();
$body = chilkat::CkJsonObject->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
#  "start" begins sign-in. "respond" submits input for the most recent saved challenge.
$action = "start";
if (($action != "start") and ($action != "respond")) {
    print "Choose start or respond." . "\r\n";
    exit;
}

$input = chilkat::CkJsonObject->new();
$input->put_Strict(1);
$success = $input->LoadFile("qa_data/cognito/signin-input.json");
if ($success != 1) {
    print "Could not load qa_data/cognito/signin-input.json." . "\r\n";
    exit;
}

if (($input->JsonTypeOf("username") != 1) or ($input->stringOf("username") == "")) {
    print "Missing or invalid username." . "\r\n";
    exit;
}

$username = $input->stringOf("username");
$body->UpdateString("ClientId",$clientId);
if ($action == "start") {
    if (($input->JsonTypeOf("password") != 1) or ($input->stringOf("password") == "")) {
        print "Missing or invalid password." . "\r\n";
        exit;
    }

    $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->get_StatusCode() != 200) {
        print "HTTP status: " . $resp->get_StatusCode() . "\r\n";
        $success = $result->Load($resp->bodyStr());
        if ($success == 1) {
            print "Error type: " . $result->stringOf("__type") . "\r\n";
            print "OAuth error: " . $result->stringOf("error") . "\r\n";
        }

        #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        exit;
    }

    if ($success != 1) {
        print "The HTTP exchange did not complete." . "\r\n";
        exit;
    }

    $success = $result->Load($resp->bodyStr());
    if ($success != 1) {
        print "Expected a JSON response." . "\r\n";
        exit;
    }

}
else {
    $challenge = chilkat::CkJsonObject->new();
    $challenge->put_Strict(1);
    $success = $challenge->LoadFile("qa_data/tokens/cognito-challenge.json");
    if ($success != 1) {
        print "Could not load qa_data/tokens/cognito-challenge.json." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("client_id") != 1) or ($challenge->stringOf("client_id") == "")) {
        print "Missing or invalid client_id." . "\r\n";
        exit;
    }

    if ($challenge->stringOf("client_id") != $app->stringOf("client_id")) {
        print "Saved data belongs to another client, pool, or local account." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("user_pool_id") != 1) or ($challenge->stringOf("user_pool_id") == "")) {
        print "Missing or invalid user_pool_id." . "\r\n";
        exit;
    }

    if ($challenge->stringOf("user_pool_id") != $app->stringOf("user_pool_id")) {
        print "Saved data belongs to another client, pool, or local account." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("account_key") != 1) or ($challenge->stringOf("account_key") == "")) {
        print "Missing or invalid account_key." . "\r\n";
        exit;
    }

    if ($challenge->stringOf("account_key") != $app->stringOf("account_key")) {
        print "Saved data belongs to another client, pool, or local account." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("Session") != 1) or ($challenge->stringOf("Session") == "")) {
        print "Missing or invalid Session." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("ChallengeName") != 1) or ($challenge->stringOf("ChallengeName") == "")) {
        print "Missing or invalid ChallengeName." . "\r\n";
        exit;
    }

    if (($challenge->JsonTypeOf("username") != 1) or ($challenge->stringOf("username") == "")) {
        print "Missing or invalid username." . "\r\n";
        exit;
    }

    #  Use the bound canonical username from the previous response, not a new alias.
    $username = $challenge->stringOf("username");
    $challengeName = $challenge->stringOf("ChallengeName");
    $body->UpdateString("Session",$challenge->stringOf("Session"));
    $body->UpdateString("ChallengeName",$challengeName);
    $body->UpdateString("ChallengeResponses.USERNAME",$username);
    if ($challengeName == "NEW_PASSWORD_REQUIRED") {
        if (($input->JsonTypeOf("new_password") != 1) or ($input->stringOf("new_password") == "")) {
            print "Missing or invalid new_password." . "\r\n";
            exit;
        }

        $body->UpdateString("ChallengeResponses.NEW_PASSWORD",$input->stringOf("new_password"));
        #  requiredAttributes is a JSON array encoded inside a JSON string.
        $requiredAttributes = chilkat::CkJsonArray->new();
        $requiredJson = $challenge->stringOf("ChallengeParameters.requiredAttributes");
        if ($challenge->HasMember("ChallengeParameters.requiredAttributes") != 1) {
            $requiredJson = "[]";
        }

        $success = $requiredAttributes->Load($requiredJson);
        if ($success != 1) {
            print "Invalid required-attributes list." . "\r\n";
            exit;
        }

        $answers = chilkat::CkJsonObject->new();
        $success = $body->ObjectOf2("ChallengeResponses",$answers);
        if ($success != 1) {
            print "Could not access challenge responses." . "\r\n";
            exit;
        }

        $i = 0;
        $count = $requiredAttributes->get_Size();

        $supplied = chilkat::CkJsonObject->new();
        if ($count > 0) {
            $success = $input->ObjectOf2("required_attributes",$supplied);
            if ($success != 1) {
                print "Supply all required attributes in required_attributes." . "\r\n";
                exit;
            }

        }

        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.
            $attributePath = chilkat::CkStringBuilder->new();
            $attributePath->Append("\"");
            $attributePath->Append($attribute);
            $attributePath->Append("\"");
            $attributeValue = $supplied->stringOf($attributePath->getAsString());
            if (($supplied->JsonTypeOf($attributePath->getAsString()) != 1) or ($attributeValue == "")) {
                print "A required user attribute is missing." . "\r\n";
                exit;
            }

            $answers->AppendString($attribute,$attributeValue);
            $i = $i + 1;
        }

    }
    else {
        if (($challengeName != "SMS_MFA") and ($challengeName != "SOFTWARE_TOKEN_MFA") and ($challengeName != "EMAIL_OTP")) {
            print "This challenge needs a different handler: " . $challengeName . "\r\n";
            #  MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
            exit;
        }

        if (($input->JsonTypeOf("code") != 1) or ($input->stringOf("code") == "")) {
            print "Missing or invalid code." . "\r\n";
            exit;
        }

        if ($challengeName == "SMS_MFA") {
            $body->UpdateString("ChallengeResponses.SMS_MFA_CODE",$input->stringOf("code"));
        }

        if ($challengeName == "SOFTWARE_TOKEN_MFA") {
            $body->UpdateString("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE",$input->stringOf("code"));
        }

        if ($challengeName == "EMAIL_OTP") {
            $body->UpdateString("ChallengeResponses.EMAIL_OTP_CODE",$input->stringOf("code"));
        }

    }

    $http->SetRequestHeader("X-Amz-Target","AWSCognitoIdentityProviderService.RespondToAuthChallenge");
    $success = $http->HttpJson("POST",$endpoint->getAsString(),$body,"application/x-amz-json-1.0",$resp);
    if ($resp->get_StatusCode() != 200) {
        print "HTTP status: " . $resp->get_StatusCode() . "\r\n";
        $success = $result->Load($resp->bodyStr());
        if ($success == 1) {
            print "Error type: " . $result->stringOf("__type") . "\r\n";
            print "OAuth error: " . $result->stringOf("error") . "\r\n";
        }

        #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        exit;
    }

    if ($success != 1) {
        print "The HTTP exchange did not complete." . "\r\n";
        exit;
    }

    $success = $result->Load($resp->bodyStr());
    if ($success != 1) {
        print "Expected a JSON response." . "\r\n";
        exit;
    }

}

if ($result->JsonTypeOf("AuthenticationResult") == 3) {
    $token = chilkat::CkJsonObject->new();
    $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") == 1) {
        $token->UpdateString("refresh_token",$result->stringOf("AuthenticationResult.RefreshToken"));
    }

    if (($token->JsonTypeOf("access_token") != 1) or ($token->stringOf("access_token") == "")) {
        print "Missing or invalid access_token." . "\r\n";
        exit;
    }

    if (($token->JsonTypeOf("id_token") != 1) or ($token->stringOf("id_token") == "")) {
        print "Missing or invalid id_token." . "\r\n";
        exit;
    }

    if (($token->JsonTypeOf("expires_in") != 2) or ($token->IntOf("expires_in") <= 0)) {
        print "Expected a positive token lifetime." . "\r\n";
        exit;
    }

    if ($token->stringOf("token_type") != "Bearer") {
        print "Expected Bearer tokens." . "\r\n";
        exit;
    }

    if (($token->JsonTypeOf("refresh_token") != 1) or ($token->stringOf("refresh_token") == "")) {
        print "Missing or invalid refresh_token." . "\r\n";
        exit;
    }

    $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"));
    $obtained = chilkat::CkDateTime->new();
    $success = $obtained->SetFromCurrentSystemTime();
    if ($success != 1) {
        print "Could not get the acquisition time." . "\r\n";
        exit;
    }

    $token->UpdateString("obtained_at",$obtained->getAsTimestamp(0));
    $tokenusertokens = chilkat::CkFileAccess->new();
    $success = $tokenusertokens->DirEnsureExists("qa_data/tokens");
    if ($success != 1) {
        print "Could not create the private cache directory." . "\r\n";
        exit;
    }

    if ($tokenusertokens->FileExists("qa_data/tokens/cognito-user.json") == 1) {
        $success = $tokenusertokens->FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",0);
        if ($success != 1) {
            print "Could not back up the existing cache." . "\r\n";
            exit;
        }

    }

    $success = $token->WriteFile("qa_data/tokens/cognito-user.json");
    if ($success != 1) {
        print "Could not save user tokens; preserve any previous backup." . "\r\n";
        exit;
    }

    #  A completed flow no longer needs its short-lived challenge session.
    $cleanup = chilkat::CkFileAccess->new();
    if ($cleanup->FileExists("qa_data/tokens/cognito-challenge.json") == 1) {
        $cleanup->FileDelete("qa_data/tokens/cognito-challenge.json");
    }

    print "Sign-in completed; private token cache saved." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("ChallengeName") != 1) or ($result->stringOf("ChallengeName") == "")) {
    print "Missing or invalid ChallengeName." . "\r\n";
    exit;
}

if (($result->JsonTypeOf("Session") != 1) or ($result->stringOf("Session") == "")) {
    print "Missing or invalid Session." . "\r\n";
    exit;
}

#  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") != "")) {
    $username = $result->stringOf("ChallengeParameters.USER_ID_FOR_SRP");
}

if (($result->JsonTypeOf("ChallengeParameters.USERNAME") == 1) and ($result->stringOf("ChallengeParameters.USERNAME") != "")) {
    $username = $result->stringOf("ChallengeParameters.USERNAME");
}

$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"));
$resultauthenticationchallenge = chilkat::CkFileAccess->new();
$success = $resultauthenticationchallenge->DirEnsureExists("qa_data/tokens");
if ($success != 1) {
    print "Could not create the private cache directory." . "\r\n";
    exit;
}

if ($resultauthenticationchallenge->FileExists("qa_data/tokens/cognito-challenge.json") == 1) {
    $success = $resultauthenticationchallenge->FileCopy("qa_data/tokens/cognito-challenge.json","qa_data/tokens/cognito-challenge.json.bak",0);
    if ($success != 1) {
        print "Could not back up the existing cache." . "\r\n";
        exit;
    }

}

$success = $result->WriteFile("qa_data/tokens/cognito-challenge.json");
if ($success != 1) {
    print "Could not save authentication challenge; preserve any previous backup." . "\r\n";
    exit;
}

print "Further authentication required: " . $result->stringOf("ChallengeName") . "\r\n";
#  Collect the requested input in your application's UI; never print the Session value.