Sample code for 30+ languages & platforms
PHP 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 PHP Downloads

PHP
<?php

use Chilkat2\DateTime;
use Chilkat2\FileAccess;
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;

$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.
$app = new JsonObject();
$app->Strict = true;
try {
    $app->LoadFile('qa_data/cognito/app.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load Cognito app settings.\n";
    exit;
}

if (($app->JsonTypeOf('region') != 1) || ($app->StringOf('region') === '')) {
    echo "Missing or invalid region.\n";
    exit;
}

if (($app->JsonTypeOf('user_pool_id') != 1) || ($app->StringOf('user_pool_id') === '')) {
    echo "Missing or invalid user_pool_id.\n";
    exit;
}

if (($app->JsonTypeOf('client_id') != 1) || ($app->StringOf('client_id') === '')) {
    echo "Missing or invalid client_id.\n";
    exit;
}

if (($app->JsonTypeOf('account_key') != 1) || ($app->StringOf('account_key') === '')) {
    echo "Missing or invalid account_key.\n";
    exit;
}

$clientId = $app->StringOf('client_id');
$endpoint = new StringBuilder();
$endpoint->Append('https://cognito-idp.');
$endpoint->Append($app->StringOf('region'));
$endpoint->Append('.amazonaws.com/');
$http = new Http();
$http->RequireSslCertVerify = true;
$http->FollowRedirects = false;
$http->ConnectTimeout = 20;
$http->ReadTimeout = 60;
$resp = new HttpResponse();
$body = new JsonObject();
$result = new JsonObject();
$result->Strict = true;
$action = 'begin';
$mode = 'signed_in';
if (($action !== 'begin') && ($action !== 'verify')) {
    echo "Choose begin or verify.\n";
    exit;
}

if (($mode !== 'signed_in') && ($mode !== 'challenge')) {
    echo "Choose signed_in or challenge.\n";
    exit;
}

$username = '';
$credential = new JsonObject();
if ($mode === 'signed_in') {
    try {
        $credential->LoadFile('qa_data/tokens/cognito-user.json');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not load user tokens.\n";
        exit;
    }

    if (($credential->JsonTypeOf('client_id') != 1) || ($credential->StringOf('client_id') === '')) {
        echo "Missing or invalid client_id.\n";
        exit;
    }

    if ($credential->StringOf('client_id') !== $app->StringOf('client_id')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('user_pool_id') != 1) || ($credential->StringOf('user_pool_id') === '')) {
        echo "Missing or invalid user_pool_id.\n";
        exit;
    }

    if ($credential->StringOf('user_pool_id') !== $app->StringOf('user_pool_id')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('account_key') != 1) || ($credential->StringOf('account_key') === '')) {
        echo "Missing or invalid account_key.\n";
        exit;
    }

    if ($credential->StringOf('account_key') !== $app->StringOf('account_key')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('access_token') != 1) || ($credential->StringOf('access_token') === '')) {
        echo "Missing or invalid access_token.\n";
        exit;
    }
} else {
    try {
        $credential->LoadFile('qa_data/tokens/cognito-challenge.json');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not load the MFA_SETUP challenge.\n";
        exit;
    }

    if (($credential->JsonTypeOf('client_id') != 1) || ($credential->StringOf('client_id') === '')) {
        echo "Missing or invalid client_id.\n";
        exit;
    }

    if ($credential->StringOf('client_id') !== $app->StringOf('client_id')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('user_pool_id') != 1) || ($credential->StringOf('user_pool_id') === '')) {
        echo "Missing or invalid user_pool_id.\n";
        exit;
    }

    if ($credential->StringOf('user_pool_id') !== $app->StringOf('user_pool_id')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('account_key') != 1) || ($credential->StringOf('account_key') === '')) {
        echo "Missing or invalid account_key.\n";
        exit;
    }

    if ($credential->StringOf('account_key') !== $app->StringOf('account_key')) {
        echo "Saved data belongs to another client, pool, or local account.\n";
        exit;
    }

    if (($credential->JsonTypeOf('Session') != 1) || ($credential->StringOf('Session') === '')) {
        echo "Missing or invalid Session.\n";
        exit;
    }

    if (($credential->JsonTypeOf('username') != 1) || ($credential->StringOf('username') === '')) {
        echo "Missing or invalid username.\n";
        exit;
    }

    if ($credential->StringOf('ChallengeName') !== 'MFA_SETUP') {
        echo "Expected an MFA_SETUP challenge.\n";
        exit;
    }

    $username = $credential->StringOf('username');
}

if ($action === 'begin') {
    if ($mode === 'signed_in') {
        $body->UpdateString('AccessToken', $credential->StringOf('access_token'));
    } else {
        $body->UpdateString('Session', $credential->StringOf('Session'));
    }

    $http->SetRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.AssociateSoftwareToken');
    $http->HttpJson('POST', $endpoint->GetAsString(), $body, 'application/x-amz-json-1.0', $resp);
    if ($resp->StatusCode != 200) {
        echo 'HTTP status: ', $resp->StatusCode, "\n";
        try {
            $result->Load($resp->BodyStr);
            $success = true;
        } catch (\Chilkat2\Exception $e) {
            $success = false;
        }
        if ($success) {
            echo 'Error type: ', $result->StringOf('__type'), "\n";
            echo 'OAuth error: ', $result->StringOf('error'), "\n";
        }

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

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

    try {
        $result->Load($resp->BodyStr);
    } catch (\Chilkat2\Exception $e) {
        echo "Expected a JSON response.\n";
        exit;
    }

    if (($result->JsonTypeOf('SecretCode') != 1) || ($result->StringOf('SecretCode') === '')) {
        echo "Missing or invalid SecretCode.\n";
        exit;
    }

    $newEnrollment = new JsonObject();
    $newEnrollment->UpdateString('secret_code', $result->StringOf('SecretCode'));
    $newEnrollment->UpdateString('mode', $mode);
    $newEnrollment->UpdateString('username', $username);
    if ($mode === 'challenge') {
        if (($result->JsonTypeOf('Session') != 1) || ($result->StringOf('Session') === '')) {
            echo "Missing or invalid Session.\n";
            exit;
        }

        $newEnrollment->UpdateString('session', $result->StringOf('Session'));
        // Bind enrollment to this precise challenge, not just the account.
        $newEnrollment->UpdateString('original_session', $credential->StringOf('Session'));
    }

    $newEnrollment->UpdateString('client_id', $app->StringOf('client_id'));
    $newEnrollment->UpdateString('user_pool_id', $app->StringOf('user_pool_id'));
    $newEnrollment->UpdateString('account_key', $app->StringOf('account_key'));
    $newEnrollmentTOTPenrollment = new FileAccess();
    try {
        $newEnrollmentTOTPenrollment->DirEnsureExists('qa_data/tokens');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not create the private cache directory.\n";
        exit;
    }

    if ($newEnrollmentTOTPenrollment->FileExists('qa_data/tokens/cognito-totp.json')) {
        try {
            $newEnrollmentTOTPenrollment->FileCopy('qa_data/tokens/cognito-totp.json', 'qa_data/tokens/cognito-totp.json.bak', false);
        } catch (\Chilkat2\Exception $e) {
            echo "Could not back up the existing cache.\n";
            exit;
        }
    }

    try {
        $newEnrollment->WriteFile('qa_data/tokens/cognito-totp.json');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not save TOTP enrollment; preserve any previous backup.\n";
        exit;
    }

    echo "Enrollment saved. Present secret_code privately in your authenticator setup UI.\n";
    // This secret can generate future OTPs. Never log it or email it.
    exit;
}

$enrollment = new JsonObject();
$enrollment->Strict = true;
try {
    $enrollment->LoadFile('qa_data/tokens/cognito-totp.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load qa_data/tokens/cognito-totp.json.\n";
    exit;
}

if (($enrollment->JsonTypeOf('client_id') != 1) || ($enrollment->StringOf('client_id') === '')) {
    echo "Missing or invalid client_id.\n";
    exit;
}

if ($enrollment->StringOf('client_id') !== $app->StringOf('client_id')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

if (($enrollment->JsonTypeOf('user_pool_id') != 1) || ($enrollment->StringOf('user_pool_id') === '')) {
    echo "Missing or invalid user_pool_id.\n";
    exit;
}

if ($enrollment->StringOf('user_pool_id') !== $app->StringOf('user_pool_id')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

if (($enrollment->JsonTypeOf('account_key') != 1) || ($enrollment->StringOf('account_key') === '')) {
    echo "Missing or invalid account_key.\n";
    exit;
}

if ($enrollment->StringOf('account_key') !== $app->StringOf('account_key')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

if ($enrollment->StringOf('mode') !== $mode) {
    echo "Enrollment mode mismatch.\n";
    exit;
}

$input = new JsonObject();
$input->Strict = true;
try {
    $input->LoadFile('qa_data/cognito/totp-input.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load qa_data/cognito/totp-input.json.\n";
    exit;
}

if (($input->JsonTypeOf('code') != 1) || ($input->StringOf('code') === '')) {
    echo "Missing or invalid code.\n";
    exit;
}

// Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
$body->UpdateString('UserCode', $input->StringOf('code'));
$body->UpdateString('FriendlyDeviceName', 'Authenticator');
if ($mode === 'signed_in') {
    $body->UpdateString('AccessToken', $credential->StringOf('access_token'));
} else {
    if (($enrollment->JsonTypeOf('session') != 1) || ($enrollment->StringOf('session') === '')) {
        echo "Missing or invalid session.\n";
        exit;
    }

    if ($enrollment->StringOf('original_session') !== $credential->StringOf('Session')) {
        echo "Enrollment belongs to another sign-in challenge.\n";
        exit;
    }

    $body->UpdateString('Session', $enrollment->StringOf('session'));
}

$http->SetRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.VerifySoftwareToken');
$http->HttpJson('POST', $endpoint->GetAsString(), $body, 'application/x-amz-json-1.0', $resp);
if ($resp->StatusCode != 200) {
    echo 'HTTP status: ', $resp->StatusCode, "\n";
    try {
        $result->Load($resp->BodyStr);
        $success = true;
    } catch (\Chilkat2\Exception $e) {
        $success = false;
    }
    if ($success) {
        echo 'Error type: ', $result->StringOf('__type'), "\n";
        echo 'OAuth error: ', $result->StringOf('error'), "\n";
    }

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

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

try {
    $result->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo "Expected a JSON response.\n";
    exit;
}

if ($result->StringOf('Status') !== 'SUCCESS') {
    echo "Authenticator verification did not succeed; do not enable it.\n";
    exit;
}

// Verification succeeded. Discard the enrollment secret and its backup.
$removeEnrollment = new FileAccess();
$removeEnrollment->FileDelete('qa_data/tokens/cognito-totp.json');
if ($removeEnrollment->FileExists('qa_data/tokens/cognito-totp.json.bak')) {
    $removeEnrollment->FileDelete('qa_data/tokens/cognito-totp.json.bak');
}

try {
    $body->Load('{}');
} catch (\Chilkat2\Exception $e) {
    echo "Could not reset the request body.\n";
    exit;
}

if ($mode === 'signed_in') {
    $body->UpdateString('AccessToken', $credential->StringOf('access_token'));
    $body->UpdateBool('SoftwareTokenMfaSettings.Enabled', true);
    $body->UpdateBool('SoftwareTokenMfaSettings.PreferredMfa', true);
    $http->SetRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.SetUserMFAPreference');
    $http->HttpJson('POST', $endpoint->GetAsString(), $body, 'application/x-amz-json-1.0', $resp);
    if ($resp->StatusCode != 200) {
        echo 'HTTP status: ', $resp->StatusCode, "\n";
        try {
            $result->Load($resp->BodyStr);
            $success = true;
        } catch (\Chilkat2\Exception $e) {
            $success = false;
        }
        if ($success) {
            echo 'Error type: ', $result->StringOf('__type'), "\n";
            echo 'OAuth error: ', $result->StringOf('error'), "\n";
        }

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

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

    echo "Authenticator verified and set as the preferred MFA method.\n";
    exit;
}

if (($result->JsonTypeOf('Session') != 1) || ($result->StringOf('Session') === '')) {
    echo "Missing or invalid Session.\n";
    exit;
}

// Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
$body->UpdateString('ClientId', $clientId);
$body->UpdateString('ChallengeName', 'MFA_SETUP');
$body->UpdateString('Session', $result->StringOf('Session'));
$body->UpdateString('ChallengeResponses.USERNAME', $username);
$http->SetRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.RespondToAuthChallenge');
$http->HttpJson('POST', $endpoint->GetAsString(), $body, 'application/x-amz-json-1.0', $resp);
if ($resp->StatusCode != 200) {
    echo 'HTTP status: ', $resp->StatusCode, "\n";
    try {
        $result->Load($resp->BodyStr);
        $success = true;
    } catch (\Chilkat2\Exception $e) {
        $success = false;
    }
    if ($success) {
        echo 'Error type: ', $result->StringOf('__type'), "\n";
        echo 'OAuth error: ', $result->StringOf('error'), "\n";
    }

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

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

try {
    $result->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo "Expected a JSON response.\n";
    exit;
}

if ($result->JsonTypeOf('AuthenticationResult') == 3) {
    $token = new JsonObject();
    $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')) {
        $token->UpdateString('refresh_token', $result->StringOf('AuthenticationResult.RefreshToken'));
    }

    if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOf('access_token') === '')) {
        echo "Missing or invalid access_token.\n";
        exit;
    }

    if (($token->JsonTypeOf('id_token') != 1) || ($token->StringOf('id_token') === '')) {
        echo "Missing or invalid id_token.\n";
        exit;
    }

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

    if ($token->StringOf('token_type') !== 'Bearer') {
        echo "Expected Bearer tokens.\n";
        exit;
    }

    if (($token->JsonTypeOf('refresh_token') != 1) || ($token->StringOf('refresh_token') === '')) {
        echo "Missing or invalid refresh_token.\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 = new DateTime();
    try {
        $obtained->SetFromCurrentSystemTime();
    } catch (\Chilkat2\Exception $e) {
        echo "Could not get the acquisition time.\n";
        exit;
    }

    $token->UpdateString('obtained_at', $obtained->GetAsTimestamp(false));
    $tokenusertokens = new FileAccess();
    try {
        $tokenusertokens->DirEnsureExists('qa_data/tokens');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not create the private cache directory.\n";
        exit;
    }

    if ($tokenusertokens->FileExists('qa_data/tokens/cognito-user.json')) {
        try {
            $tokenusertokens->FileCopy('qa_data/tokens/cognito-user.json', 'qa_data/tokens/cognito-user.json.bak', false);
        } catch (\Chilkat2\Exception $e) {
            echo "Could not back up the existing cache.\n";
            exit;
        }
    }

    try {
        $token->WriteFile('qa_data/tokens/cognito-user.json');
    } catch (\Chilkat2\Exception $e) {
        echo "Could not save user tokens; preserve any previous backup.\n";
        exit;
    }

    // A completed flow no longer needs its short-lived challenge session.
    $cleanup = new FileAccess();
    if ($cleanup->FileExists('qa_data/tokens/cognito-challenge.json')) {
        $cleanup->FileDelete('qa_data/tokens/cognito-challenge.json');
    }

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

if (($result->JsonTypeOf('ChallengeName') != 1) || ($result->StringOf('ChallengeName') === '')) {
    echo "Missing or invalid ChallengeName.\n";
    exit;
}

if (($result->JsonTypeOf('Session') != 1) || ($result->StringOf('Session') === '')) {
    echo "Missing or invalid Session.\n";
    exit;
}

// ChallengeParameters may provide the canonical username after alias-based sign-in.
if (($result->JsonTypeOf('ChallengeParameters.USER_ID_FOR_SRP') == 1) && ($result->StringOf('ChallengeParameters.USER_ID_FOR_SRP') !== '')) {
    $username = $result->StringOf('ChallengeParameters.USER_ID_FOR_SRP');
}

if (($result->JsonTypeOf('ChallengeParameters.USERNAME') == 1) && ($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 = new FileAccess();
try {
    $resultauthenticationchallenge->DirEnsureExists('qa_data/tokens');
} catch (\Chilkat2\Exception $e) {
    echo "Could not create the private cache directory.\n";
    exit;
}

if ($resultauthenticationchallenge->FileExists('qa_data/tokens/cognito-challenge.json')) {
    try {
        $resultauthenticationchallenge->FileCopy('qa_data/tokens/cognito-challenge.json', 'qa_data/tokens/cognito-challenge.json.bak', false);
    } catch (\Chilkat2\Exception $e) {
        echo "Could not back up the existing cache.\n";
        exit;
    }
}

try {
    $result->WriteFile('qa_data/tokens/cognito-challenge.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not save authentication challenge; preserve any previous backup.\n";
    exit;
}

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