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

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean 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.
        JsonObject app = new JsonObject();
        app.setStrict(true);
        try {
            app.loadFile("qa_data/cognito/app.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load Cognito app settings.");
            return;
        }

        if ((app.jsonTypeOf("region") != 1) || ("".equals(app.stringOf("region")))) {
            System.out.println("Missing or invalid region.");
            return;
        }

        if ((app.jsonTypeOf("user_pool_id") != 1) || ("".equals(app.stringOf("user_pool_id")))) {
            System.out.println("Missing or invalid user_pool_id.");
            return;
        }

        if ((app.jsonTypeOf("client_id") != 1) || ("".equals(app.stringOf("client_id")))) {
            System.out.println("Missing or invalid client_id.");
            return;
        }

        if ((app.jsonTypeOf("account_key") != 1) || ("".equals(app.stringOf("account_key")))) {
            System.out.println("Missing or invalid account_key.");
            return;
        }

        String clientId = app.stringOf("client_id");
        StringBuilder endpoint = new StringBuilder();
        endpoint.append("https://cognito-idp.");
        endpoint.append(app.stringOf("region"));
        endpoint.append(".amazonaws.com/");
        Http http = new Http();
        http.setRequireSslCertVerify(true);
        http.setFollowRedirects(false);
        http.setConnectTimeout(20);
        http.setReadTimeout(60);
        HttpResponse resp = new HttpResponse();
        JsonObject body = new JsonObject();
        JsonObject result = new JsonObject();
        result.setStrict(true);
        String action = "begin";
        String mode = "signed_in";
        if ((!"begin".equals(action)) && (!"verify".equals(action))) {
            System.out.println("Choose begin or verify.");
            return;
        }

        if ((!"signed_in".equals(mode)) && (!"challenge".equals(mode))) {
            System.out.println("Choose signed_in or challenge.");
            return;
        }

        String username = "";
        JsonObject credential = new JsonObject();
        if ("signed_in".equals(mode)) {
            try {
                credential.loadFile("qa_data/tokens/cognito-user.json");
            } catch (ChilkatException e) {
                System.out.println("Could not load user tokens.");
                return;
            }

            if ((credential.jsonTypeOf("client_id") != 1) || ("".equals(credential.stringOf("client_id")))) {
                System.out.println("Missing or invalid client_id.");
                return;
            }

            if (!credential.stringOf("client_id").equals(app.stringOf("client_id"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("user_pool_id") != 1) || ("".equals(credential.stringOf("user_pool_id")))) {
                System.out.println("Missing or invalid user_pool_id.");
                return;
            }

            if (!credential.stringOf("user_pool_id").equals(app.stringOf("user_pool_id"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("account_key") != 1) || ("".equals(credential.stringOf("account_key")))) {
                System.out.println("Missing or invalid account_key.");
                return;
            }

            if (!credential.stringOf("account_key").equals(app.stringOf("account_key"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("access_token") != 1) || ("".equals(credential.stringOf("access_token")))) {
                System.out.println("Missing or invalid access_token.");
                return;
            }
        } else {
            try {
                credential.loadFile("qa_data/tokens/cognito-challenge.json");
            } catch (ChilkatException e) {
                System.out.println("Could not load the MFA_SETUP challenge.");
                return;
            }

            if ((credential.jsonTypeOf("client_id") != 1) || ("".equals(credential.stringOf("client_id")))) {
                System.out.println("Missing or invalid client_id.");
                return;
            }

            if (!credential.stringOf("client_id").equals(app.stringOf("client_id"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("user_pool_id") != 1) || ("".equals(credential.stringOf("user_pool_id")))) {
                System.out.println("Missing or invalid user_pool_id.");
                return;
            }

            if (!credential.stringOf("user_pool_id").equals(app.stringOf("user_pool_id"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("account_key") != 1) || ("".equals(credential.stringOf("account_key")))) {
                System.out.println("Missing or invalid account_key.");
                return;
            }

            if (!credential.stringOf("account_key").equals(app.stringOf("account_key"))) {
                System.out.println("Saved data belongs to another client, pool, or local account.");
                return;
            }

            if ((credential.jsonTypeOf("Session") != 1) || ("".equals(credential.stringOf("Session")))) {
                System.out.println("Missing or invalid Session.");
                return;
            }

            if ((credential.jsonTypeOf("username") != 1) || ("".equals(credential.stringOf("username")))) {
                System.out.println("Missing or invalid username.");
                return;
            }

            if (!"MFA_SETUP".equals(credential.stringOf("ChallengeName"))) {
                System.out.println("Expected an MFA_SETUP challenge.");
                return;
            }

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

        if ("begin".equals(action)) {
            if ("signed_in".equals(mode)) {
                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.getStatusCode() != 200) {
                System.out.println("HTTP status: " + resp.getStatusCode());
                try {
                    result.load(resp.getBodyStr());
                    success = true;
                } catch (ChilkatException e) {
                    success = false;
                }
                if (success) {
                    System.out.println("Error type: " + result.stringOf("__type"));
                    System.out.println("OAuth error: " + result.stringOf("error"));
                }

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

            if (!success) {
                System.out.println("The HTTP exchange did not complete.");
                return;
            }

            try {
                result.load(resp.getBodyStr());
            } catch (ChilkatException e) {
                System.out.println("Expected a JSON response.");
                return;
            }

            if ((result.jsonTypeOf("SecretCode") != 1) || ("".equals(result.stringOf("SecretCode")))) {
                System.out.println("Missing or invalid SecretCode.");
                return;
            }

            JsonObject newEnrollment = new JsonObject();
            newEnrollment.updateString("secret_code", result.stringOf("SecretCode"));
            newEnrollment.updateString("mode", mode);
            newEnrollment.updateString("username", username);
            if ("challenge".equals(mode)) {
                if ((result.jsonTypeOf("Session") != 1) || ("".equals(result.stringOf("Session")))) {
                    System.out.println("Missing or invalid Session.");
                    return;
                }

                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"));
            FileAccess newEnrollmentTOTPenrollment = new FileAccess();
            try {
                newEnrollmentTOTPenrollment.dirEnsureExists("qa_data/tokens");
            } catch (ChilkatException e) {
                System.out.println("Could not create the private cache directory.");
                return;
            }

            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 (ChilkatException e) {
                    System.out.println("Could not back up the existing cache.");
                    return;
                }
            }

            try {
                newEnrollment.writeFile("qa_data/tokens/cognito-totp.json");
            } catch (ChilkatException e) {
                System.out.println("Could not save TOTP enrollment; preserve any previous backup.");
                return;
            }

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

        JsonObject enrollment = new JsonObject();
        enrollment.setStrict(true);
        try {
            enrollment.loadFile("qa_data/tokens/cognito-totp.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load qa_data/tokens/cognito-totp.json.");
            return;
        }

        if ((enrollment.jsonTypeOf("client_id") != 1) || ("".equals(enrollment.stringOf("client_id")))) {
            System.out.println("Missing or invalid client_id.");
            return;
        }

        if (!enrollment.stringOf("client_id").equals(app.stringOf("client_id"))) {
            System.out.println("Saved data belongs to another client, pool, or local account.");
            return;
        }

        if ((enrollment.jsonTypeOf("user_pool_id") != 1) || ("".equals(enrollment.stringOf("user_pool_id")))) {
            System.out.println("Missing or invalid user_pool_id.");
            return;
        }

        if (!enrollment.stringOf("user_pool_id").equals(app.stringOf("user_pool_id"))) {
            System.out.println("Saved data belongs to another client, pool, or local account.");
            return;
        }

        if ((enrollment.jsonTypeOf("account_key") != 1) || ("".equals(enrollment.stringOf("account_key")))) {
            System.out.println("Missing or invalid account_key.");
            return;
        }

        if (!enrollment.stringOf("account_key").equals(app.stringOf("account_key"))) {
            System.out.println("Saved data belongs to another client, pool, or local account.");
            return;
        }

        if (!enrollment.stringOf("mode").equals(mode)) {
            System.out.println("Enrollment mode mismatch.");
            return;
        }

        JsonObject input = new JsonObject();
        input.setStrict(true);
        try {
            input.loadFile("qa_data/cognito/totp-input.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load qa_data/cognito/totp-input.json.");
            return;
        }

        if ((input.jsonTypeOf("code") != 1) || ("".equals(input.stringOf("code")))) {
            System.out.println("Missing or invalid code.");
            return;
        }

        // Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
        body.updateString("UserCode", input.stringOf("code"));
        body.updateString("FriendlyDeviceName", "Authenticator");
        if ("signed_in".equals(mode)) {
            body.updateString("AccessToken", credential.stringOf("access_token"));
        } else {
            if ((enrollment.jsonTypeOf("session") != 1) || ("".equals(enrollment.stringOf("session")))) {
                System.out.println("Missing or invalid session.");
                return;
            }

            if (!enrollment.stringOf("original_session").equals(credential.stringOf("Session"))) {
                System.out.println("Enrollment belongs to another sign-in challenge.");
                return;
            }

            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.getStatusCode() != 200) {
            System.out.println("HTTP status: " + resp.getStatusCode());
            try {
                result.load(resp.getBodyStr());
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                System.out.println("Error type: " + result.stringOf("__type"));
                System.out.println("OAuth error: " + result.stringOf("error"));
            }

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

        if (!success) {
            System.out.println("The HTTP exchange did not complete.");
            return;
        }

        try {
            result.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Expected a JSON response.");
            return;
        }

        if (!"SUCCESS".equals(result.stringOf("Status"))) {
            System.out.println("Authenticator verification did not succeed; do not enable it.");
            return;
        }

        // Verification succeeded. Discard the enrollment secret and its backup.
        FileAccess 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 (ChilkatException e) {
            System.out.println("Could not reset the request body.");
            return;
        }

        if ("signed_in".equals(mode)) {
            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.getStatusCode() != 200) {
                System.out.println("HTTP status: " + resp.getStatusCode());
                try {
                    result.load(resp.getBodyStr());
                    success = true;
                } catch (ChilkatException e) {
                    success = false;
                }
                if (success) {
                    System.out.println("Error type: " + result.stringOf("__type"));
                    System.out.println("OAuth error: " + result.stringOf("error"));
                }

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

            if (!success) {
                System.out.println("The HTTP exchange did not complete.");
                return;
            }

            System.out.println("Authenticator verified and set as the preferred MFA method.");
            return;
        }

        if ((result.jsonTypeOf("Session") != 1) || ("".equals(result.stringOf("Session")))) {
            System.out.println("Missing or invalid Session.");
            return;
        }

        // 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.getStatusCode() != 200) {
            System.out.println("HTTP status: " + resp.getStatusCode());
            try {
                result.load(resp.getBodyStr());
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (success) {
                System.out.println("Error type: " + result.stringOf("__type"));
                System.out.println("OAuth error: " + result.stringOf("error"));
            }

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

        if (!success) {
            System.out.println("The HTTP exchange did not complete.");
            return;
        }

        try {
            result.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Expected a JSON response.");
            return;
        }

        if (result.jsonTypeOf("AuthenticationResult") == 3) {
            JsonObject 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) || ("".equals(token.stringOf("access_token")))) {
                System.out.println("Missing or invalid access_token.");
                return;
            }

            if ((token.jsonTypeOf("id_token") != 1) || ("".equals(token.stringOf("id_token")))) {
                System.out.println("Missing or invalid id_token.");
                return;
            }

            if ((token.jsonTypeOf("expires_in") != 2) || (token.intOf("expires_in") <= 0)) {
                System.out.println("Expected a positive token lifetime.");
                return;
            }

            if (!"Bearer".equals(token.stringOf("token_type"))) {
                System.out.println("Expected Bearer tokens.");
                return;
            }

            if ((token.jsonTypeOf("refresh_token") != 1) || ("".equals(token.stringOf("refresh_token")))) {
                System.out.println("Missing or invalid refresh_token.");
                return;
            }

            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"));
            DateTime obtained = new DateTime();
            try {
                obtained.setFromCurrentSystemTime();
            } catch (ChilkatException e) {
                System.out.println("Could not get the acquisition time.");
                return;
            }

            token.updateString("obtained_at", obtained.getAsTimestamp(false));
            FileAccess tokenusertokens = new FileAccess();
            try {
                tokenusertokens.dirEnsureExists("qa_data/tokens");
            } catch (ChilkatException e) {
                System.out.println("Could not create the private cache directory.");
                return;
            }

            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 (ChilkatException e) {
                    System.out.println("Could not back up the existing cache.");
                    return;
                }
            }

            try {
                token.writeFile("qa_data/tokens/cognito-user.json");
            } catch (ChilkatException e) {
                System.out.println("Could not save user tokens; preserve any previous backup.");
                return;
            }

            // A completed flow no longer needs its short-lived challenge session.
            FileAccess cleanup = new FileAccess();
            if (cleanup.fileExists("qa_data/tokens/cognito-challenge.json")) {
                cleanup.fileDelete("qa_data/tokens/cognito-challenge.json");
            }

            System.out.println("Sign-in completed; private token cache saved.");
            return;
        }

        if ((result.jsonTypeOf("ChallengeName") != 1) || ("".equals(result.stringOf("ChallengeName")))) {
            System.out.println("Missing or invalid ChallengeName.");
            return;
        }

        if ((result.jsonTypeOf("Session") != 1) || ("".equals(result.stringOf("Session")))) {
            System.out.println("Missing or invalid Session.");
            return;
        }

        // ChallengeParameters may provide the canonical username after alias-based sign-in.
        if ((result.jsonTypeOf("ChallengeParameters.USER_ID_FOR_SRP") == 1) && (!"".equals(result.stringOf("ChallengeParameters.USER_ID_FOR_SRP")))) {
            username = result.stringOf("ChallengeParameters.USER_ID_FOR_SRP");
        }

        if ((result.jsonTypeOf("ChallengeParameters.USERNAME") == 1) && (!"".equals(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"));
        FileAccess resultauthenticationchallenge = new FileAccess();
        try {
            resultauthenticationchallenge.dirEnsureExists("qa_data/tokens");
        } catch (ChilkatException e) {
            System.out.println("Could not create the private cache directory.");
            return;
        }

        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 (ChilkatException e) {
                System.out.println("Could not back up the existing cache.");
                return;
            }
        }

        try {
            result.writeFile("qa_data/tokens/cognito-challenge.json");
        } catch (ChilkatException e) {
            System.out.println("Could not save authentication challenge; preserve any previous backup.");
            return;
        }

        System.out.println("Further authentication required: " + result.stringOf("ChallengeName"));
        // Collect the requested input in your application's UI; never print the Session value.
    }
}