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

Unicode C++
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkFileAccessW.h>
#include <CkDateTimeW.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);
    const wchar_t *action = L"begin";
    const wchar_t *mode = L"signed_in";
    if ((action != L"begin") && (action != L"verify")) {
        wprintf(L"Choose begin or verify.\n");
        return;
    }

    if ((mode != L"signed_in") && (mode != L"challenge")) {
        wprintf(L"Choose signed_in or challenge.\n");
        return;
    }

    const wchar_t *username = L"";
    CkJsonObjectW credential;
    if (mode == L"signed_in") {
        success = credential.LoadFile(L"qa_data/tokens/cognito-user.json");
        if (success != true) {
            wprintf(L"Could not load user tokens.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"client_id") != 1) || (credential.stringOf(L"client_id") == L"")) {
            wprintf(L"Missing or invalid client_id.\n");
            return;
        }

        if (credential.stringOf(L"client_id") != app.stringOf(L"client_id")) {
            wprintf(L"Saved data belongs to another client, pool, or local account.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"user_pool_id") != 1) || (credential.stringOf(L"user_pool_id") == L"")) {
            wprintf(L"Missing or invalid user_pool_id.\n");
            return;
        }

        if (credential.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 ((credential.JsonTypeOf(L"account_key") != 1) || (credential.stringOf(L"account_key") == L"")) {
            wprintf(L"Missing or invalid account_key.\n");
            return;
        }

        if (credential.stringOf(L"account_key") != app.stringOf(L"account_key")) {
            wprintf(L"Saved data belongs to another client, pool, or local account.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"access_token") != 1) || (credential.stringOf(L"access_token") == L"")) {
            wprintf(L"Missing or invalid access_token.\n");
            return;
        }

    }
    else {
        success = credential.LoadFile(L"qa_data/tokens/cognito-challenge.json");
        if (success != true) {
            wprintf(L"Could not load the MFA_SETUP challenge.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"client_id") != 1) || (credential.stringOf(L"client_id") == L"")) {
            wprintf(L"Missing or invalid client_id.\n");
            return;
        }

        if (credential.stringOf(L"client_id") != app.stringOf(L"client_id")) {
            wprintf(L"Saved data belongs to another client, pool, or local account.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"user_pool_id") != 1) || (credential.stringOf(L"user_pool_id") == L"")) {
            wprintf(L"Missing or invalid user_pool_id.\n");
            return;
        }

        if (credential.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 ((credential.JsonTypeOf(L"account_key") != 1) || (credential.stringOf(L"account_key") == L"")) {
            wprintf(L"Missing or invalid account_key.\n");
            return;
        }

        if (credential.stringOf(L"account_key") != app.stringOf(L"account_key")) {
            wprintf(L"Saved data belongs to another client, pool, or local account.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"Session") != 1) || (credential.stringOf(L"Session") == L"")) {
            wprintf(L"Missing or invalid Session.\n");
            return;
        }

        if ((credential.JsonTypeOf(L"username") != 1) || (credential.stringOf(L"username") == L"")) {
            wprintf(L"Missing or invalid username.\n");
            return;
        }

        if (credential.stringOf(L"ChallengeName") != L"MFA_SETUP") {
            wprintf(L"Expected an MFA_SETUP challenge.\n");
            return;
        }

        username = credential.stringOf(L"username");
    }

    if (action == L"begin") {
        if (mode == L"signed_in") {
            body.UpdateString(L"AccessToken",credential.stringOf(L"access_token"));
        }
        else {
            body.UpdateString(L"Session",credential.stringOf(L"Session"));
        }

        http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.AssociateSoftwareToken");
        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"SecretCode") != 1) || (result.stringOf(L"SecretCode") == L"")) {
            wprintf(L"Missing or invalid SecretCode.\n");
            return;
        }

        CkJsonObjectW newEnrollment;
        newEnrollment.UpdateString(L"secret_code",result.stringOf(L"SecretCode"));
        newEnrollment.UpdateString(L"mode",mode);
        newEnrollment.UpdateString(L"username",username);
        if (mode == L"challenge") {
            if ((result.JsonTypeOf(L"Session") != 1) || (result.stringOf(L"Session") == L"")) {
                wprintf(L"Missing or invalid Session.\n");
                return;
            }

            newEnrollment.UpdateString(L"session",result.stringOf(L"Session"));
            //  Bind enrollment to this precise challenge, not just the account.
            newEnrollment.UpdateString(L"original_session",credential.stringOf(L"Session"));
        }

        newEnrollment.UpdateString(L"client_id",app.stringOf(L"client_id"));
        newEnrollment.UpdateString(L"user_pool_id",app.stringOf(L"user_pool_id"));
        newEnrollment.UpdateString(L"account_key",app.stringOf(L"account_key"));
        CkFileAccessW newEnrollmentTOTPenrollment;
        success = newEnrollmentTOTPenrollment.DirEnsureExists(L"qa_data/tokens");
        if (success != true) {
            wprintf(L"Could not create the private cache directory.\n");
            return;
        }

        if (newEnrollmentTOTPenrollment.FileExists(L"qa_data/tokens/cognito-totp.json") == true) {
            success = newEnrollmentTOTPenrollment.FileCopy(L"qa_data/tokens/cognito-totp.json",L"qa_data/tokens/cognito-totp.json.bak",false);
            if (success != true) {
                wprintf(L"Could not back up the existing cache.\n");
                return;
            }

        }

        success = newEnrollment.WriteFile(L"qa_data/tokens/cognito-totp.json");
        if (success != true) {
            wprintf(L"Could not save TOTP enrollment; preserve any previous backup.\n");
            return;
        }

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

    CkJsonObjectW enrollment;
    enrollment.put_Strict(true);
    success = enrollment.LoadFile(L"qa_data/tokens/cognito-totp.json");
    if (success != true) {
        wprintf(L"Could not load qa_data/tokens/cognito-totp.json.\n");
        return;
    }

    if ((enrollment.JsonTypeOf(L"client_id") != 1) || (enrollment.stringOf(L"client_id") == L"")) {
        wprintf(L"Missing or invalid client_id.\n");
        return;
    }

    if (enrollment.stringOf(L"client_id") != app.stringOf(L"client_id")) {
        wprintf(L"Saved data belongs to another client, pool, or local account.\n");
        return;
    }

    if ((enrollment.JsonTypeOf(L"user_pool_id") != 1) || (enrollment.stringOf(L"user_pool_id") == L"")) {
        wprintf(L"Missing or invalid user_pool_id.\n");
        return;
    }

    if (enrollment.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 ((enrollment.JsonTypeOf(L"account_key") != 1) || (enrollment.stringOf(L"account_key") == L"")) {
        wprintf(L"Missing or invalid account_key.\n");
        return;
    }

    if (enrollment.stringOf(L"account_key") != app.stringOf(L"account_key")) {
        wprintf(L"Saved data belongs to another client, pool, or local account.\n");
        return;
    }

    if (enrollment.stringOf(L"mode") != mode) {
        wprintf(L"Enrollment mode mismatch.\n");
        return;
    }

    CkJsonObjectW input;
    input.put_Strict(true);
    success = input.LoadFile(L"qa_data/cognito/totp-input.json");
    if (success != true) {
        wprintf(L"Could not load qa_data/cognito/totp-input.json.\n");
        return;
    }

    if ((input.JsonTypeOf(L"code") != 1) || (input.stringOf(L"code") == L"")) {
        wprintf(L"Missing or invalid code.\n");
        return;
    }

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

        if (enrollment.stringOf(L"original_session") != credential.stringOf(L"Session")) {
            wprintf(L"Enrollment belongs to another sign-in challenge.\n");
            return;
        }

        body.UpdateString(L"Session",enrollment.stringOf(L"session"));
    }

    http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.VerifySoftwareToken");
    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.stringOf(L"Status") != L"SUCCESS") {
        wprintf(L"Authenticator verification did not succeed; do not enable it.\n");
        return;
    }

    //  Verification succeeded. Discard the enrollment secret and its backup.
    CkFileAccessW removeEnrollment;
    removeEnrollment.FileDelete(L"qa_data/tokens/cognito-totp.json");
    if (removeEnrollment.FileExists(L"qa_data/tokens/cognito-totp.json.bak") == true) {
        removeEnrollment.FileDelete(L"qa_data/tokens/cognito-totp.json.bak");
    }

    success = body.Load(L"{}");
    if (success != true) {
        wprintf(L"Could not reset the request body.\n");
        return;
    }

    if (mode == L"signed_in") {
        body.UpdateString(L"AccessToken",credential.stringOf(L"access_token"));
        body.UpdateBool(L"SoftwareTokenMfaSettings.Enabled",true);
        body.UpdateBool(L"SoftwareTokenMfaSettings.PreferredMfa",true);
        http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.SetUserMFAPreference");
        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;
        }

        wprintf(L"Authenticator verified and set as the preferred MFA method.\n");
        return;
    }

    if ((result.JsonTypeOf(L"Session") != 1) || (result.stringOf(L"Session") == L"")) {
        wprintf(L"Missing or invalid Session.\n");
        return;
    }

    //  Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
    body.UpdateString(L"ClientId",clientId);
    body.UpdateString(L"ChallengeName",L"MFA_SETUP");
    body.UpdateString(L"Session",result.stringOf(L"Session"));
    body.UpdateString(L"ChallengeResponses.USERNAME",username);
    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.
    }