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

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    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.
    CkJsonObject app = new CkJsonObject();
    app.put_Strict(true);
    success = app.LoadFile("qa_data/cognito/app.json");
    if (success != true) {
        System.out.println("Could not load Cognito app settings.");
        return;
        }

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

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

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

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

    String clientId = app.stringOf("client_id");
    CkStringBuilder endpoint = new CkStringBuilder();
    endpoint.Append("https://cognito-idp.");
    endpoint.Append(app.stringOf("region"));
    endpoint.Append(".amazonaws.com/");
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    CkHttpResponse resp = new CkHttpResponse();
    CkJsonObject body = new CkJsonObject();
    CkJsonObject result = new CkJsonObject();
    result.put_Strict(true);
    String action = "begin";
    String mode = "signed_in";
    if ((action != "begin") && (action != "verify")) {
        System.out.println("Choose begin or verify.");
        return;
        }

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

    String username = "";
    CkJsonObject credential = new CkJsonObject();
    if (mode == "signed_in") {
        success = credential.LoadFile("qa_data/tokens/cognito-user.json");
        if (success != true) {
            System.out.println("Could not load user tokens.");
            return;
            }

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

        if (credential.stringOf("client_id") != 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) || (credential.stringOf("user_pool_id") == "")) {
            System.out.println("Missing or invalid user_pool_id.");
            return;
            }

        if (credential.stringOf("user_pool_id") != 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) || (credential.stringOf("account_key") == "")) {
            System.out.println("Missing or invalid account_key.");
            return;
            }

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

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

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

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

        if (credential.stringOf("client_id") != 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) || (credential.stringOf("user_pool_id") == "")) {
            System.out.println("Missing or invalid user_pool_id.");
            return;
            }

        if (credential.stringOf("user_pool_id") != 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) || (credential.stringOf("account_key") == "")) {
            System.out.println("Missing or invalid account_key.");
            return;
            }

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

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

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

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

        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");
        success = http.HttpJson("POST",endpoint.getAsString(),body,"application/x-amz-json-1.0",resp);
        if (resp.get_StatusCode() != 200) {
            System.out.println("HTTP status: " + resp.get_StatusCode());
            success = result.Load(resp.bodyStr());
            if (success == true) {
                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 != true) {
            System.out.println("The HTTP exchange did not complete.");
            return;
            }

        success = result.Load(resp.bodyStr());
        if (success != true) {
            System.out.println("Expected a JSON response.");
            return;
            }

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

        CkJsonObject newEnrollment = new CkJsonObject();
        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") == "")) {
                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"));
        CkFileAccess newEnrollmentTOTPenrollment = new CkFileAccess();
        success = newEnrollmentTOTPenrollment.DirEnsureExists("qa_data/tokens");
        if (success != true) {
            System.out.println("Could not create the private cache directory.");
            return;
            }

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

            }

        success = newEnrollment.WriteFile("qa_data/tokens/cognito-totp.json");
        if (success != true) {
            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;
        }

    CkJsonObject enrollment = new CkJsonObject();
    enrollment.put_Strict(true);
    success = enrollment.LoadFile("qa_data/tokens/cognito-totp.json");
    if (success != true) {
        System.out.println("Could not load qa_data/tokens/cognito-totp.json.");
        return;
        }

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

    if (enrollment.stringOf("client_id") != 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) || (enrollment.stringOf("user_pool_id") == "")) {
        System.out.println("Missing or invalid user_pool_id.");
        return;
        }

    if (enrollment.stringOf("user_pool_id") != 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) || (enrollment.stringOf("account_key") == "")) {
        System.out.println("Missing or invalid account_key.");
        return;
        }

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

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

    CkJsonObject input = new CkJsonObject();
    input.put_Strict(true);
    success = input.LoadFile("qa_data/cognito/totp-input.json");
    if (success != true) {
        System.out.println("Could not load qa_data/cognito/totp-input.json.");
        return;
        }

    if ((input.JsonTypeOf("code") != 1) || (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 (mode == "signed_in") {
        body.UpdateString("AccessToken",credential.stringOf("access_token"));
        }
    else {
        if ((enrollment.JsonTypeOf("session") != 1) || (enrollment.stringOf("session") == "")) {
            System.out.println("Missing or invalid session.");
            return;
            }

        if (enrollment.stringOf("original_session") != 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");
    success = http.HttpJson("POST",endpoint.getAsString(),body,"application/x-amz-json-1.0",resp);
    if (resp.get_StatusCode() != 200) {
        System.out.println("HTTP status: " + resp.get_StatusCode());
        success = result.Load(resp.bodyStr());
        if (success == true) {
            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 != true) {
        System.out.println("The HTTP exchange did not complete.");
        return;
        }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Expected a JSON response.");
        return;
        }

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

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

    success = body.Load("{}");
    if (success != true) {
        System.out.println("Could not reset the request body.");
        return;
        }

    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");
        success = http.HttpJson("POST",endpoint.getAsString(),body,"application/x-amz-json-1.0",resp);
        if (resp.get_StatusCode() != 200) {
            System.out.println("HTTP status: " + resp.get_StatusCode());
            success = result.Load(resp.bodyStr());
            if (success == true) {
                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 != true) {
            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) || (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");
    success = http.HttpJson("POST",endpoint.getAsString(),body,"application/x-amz-json-1.0",resp);
    if (resp.get_StatusCode() != 200) {
        System.out.println("HTTP status: " + resp.get_StatusCode());
        success = result.Load(resp.bodyStr());
        if (success == true) {
            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 != true) {
        System.out.println("The HTTP exchange did not complete.");
        return;
        }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Expected a JSON response.");
        return;
        }

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

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

        if ((token.JsonTypeOf("id_token") != 1) || (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 (token.stringOf("token_type") != "Bearer") {
            System.out.println("Expected Bearer tokens.");
            return;
            }

        if ((token.JsonTypeOf("refresh_token") != 1) || (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"));
        CkDateTime obtained = new CkDateTime();
        success = obtained.SetFromCurrentSystemTime();
        if (success != true) {
            System.out.println("Could not get the acquisition time.");
            return;
            }

        token.UpdateString("obtained_at",obtained.getAsTimestamp(false));
        CkFileAccess tokenusertokens = new CkFileAccess();
        success = tokenusertokens.DirEnsureExists("qa_data/tokens");
        if (success != true) {
            System.out.println("Could not create the private cache directory.");
            return;
            }

        if (tokenusertokens.FileExists("qa_data/tokens/cognito-user.json") == true) {
            success = tokenusertokens.FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",false);
            if (success != true) {
                System.out.println("Could not back up the existing cache.");
                return;
                }

            }

        success = token.WriteFile("qa_data/tokens/cognito-user.json");
        if (success != true) {
            System.out.println("Could not save user tokens; preserve any previous backup.");
            return;
            }

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

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

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

    if ((result.JsonTypeOf("Session") != 1) || (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) && (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"));
    CkFileAccess resultauthenticationchallenge = new CkFileAccess();
    success = resultauthenticationchallenge.DirEnsureExists("qa_data/tokens");
    if (success != true) {
        System.out.println("Could not create the private cache directory.");
        return;
        }

    if (resultauthenticationchallenge.FileExists("qa_data/tokens/cognito-challenge.json") == true) {
        success = resultauthenticationchallenge.FileCopy("qa_data/tokens/cognito-challenge.json","qa_data/tokens/cognito-challenge.json.bak",false);
        if (success != true) {
            System.out.println("Could not back up the existing cache.");
            return;
            }

        }

    success = result.WriteFile("qa_data/tokens/cognito-challenge.json");
    if (success != true) {
        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.
  }
}