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

Amazon Cognito: Sign In and Respond to Password or MFA Challenges

See more Amazon Cognito Examples

Enable ALLOW_USER_PASSWORD_AUTH on a public app client without a secret; use a password-based pool with device remembering disabled. Managed login with PKCE is preferable when your application need not handle passwords. This example illustrates the JSON API directly: start with username/password, then respond to each returned challenge with its latest Session. It does not implement SRP, remembered-device authentication, passkeys, custom challenges, or every possible challenge.

Set action=start with a private signin-input.json containing username and password. For respond, supply username plus new_password or code. NEW_PASSWORD_REQUIRED can also require a required_attributes object keyed by the names in ChallengeParameters.requiredAttributes, for example "userAttributes.email". Supply only requested missing attributes; existing required attributes cannot be changed during this challenge. Handles NEW_PASSWORD_REQUIRED, SMS_MFA, SOFTWARE_TOKEN_MFA and EMAIL_OTP. MFA_SETUP is handed to TOTP enrollment. Other challenges stop explicitly.

The latest challenge is saved privately with the canonical username and app/account binding. Only AuthenticationResult constitutes completed sign-in; a Session is not an access token. Confirmation codes remain strings, preserving leading zeroes. On timeout/expired session start again; do not reuse a session across users or parallel flows.

Uses direct Chilkat.Http requests to the regional Cognito User Pools JSON API. Public app-client operations do not use IAM signing. These examples use a public app client without a client secret; do not add administrative AWS credentials. For a confidential app client, implement the operation-specific SecretHash/SECRET_HASH or ClientSecret requirements on a trusted system.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1 | AWS documentation 2

Chilkat 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.JsonArray;
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);
        // "start" begins sign-in. "respond" submits input for the most recent saved challenge.
        String action = "start";
        if ((!"start".equals(action)) && (!"respond".equals(action))) {
            System.out.println("Choose start or respond.");
            return;
        }

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

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

        String username = input.stringOf("username");
        body.updateString("ClientId", clientId);
        if ("start".equals(action)) {
            if ((input.jsonTypeOf("password") != 1) || ("".equals(input.stringOf("password")))) {
                System.out.println("Missing or invalid password.");
                return;
            }

            body.updateString("AuthFlow", "USER_PASSWORD_AUTH");
            body.updateString("AuthParameters.USERNAME", username);
            body.updateString("AuthParameters.PASSWORD", input.stringOf("password"));
            http.setRequestHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth");
            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;
            }
        } else {
            JsonObject challenge = new JsonObject();
            challenge.setStrict(true);
            try {
                challenge.loadFile("qa_data/tokens/cognito-challenge.json");
            } catch (ChilkatException e) {
                System.out.println("Could not load qa_data/tokens/cognito-challenge.json.");
                return;
            }

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

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

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

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

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

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

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

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

            // Use the bound canonical username from the previous response, not a new alias.
            username = challenge.stringOf("username");
            String challengeName = challenge.stringOf("ChallengeName");
            body.updateString("Session", challenge.stringOf("Session"));
            body.updateString("ChallengeName", challengeName);
            body.updateString("ChallengeResponses.USERNAME", username);
            if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
                if ((input.jsonTypeOf("new_password") != 1) || ("".equals(input.stringOf("new_password")))) {
                    System.out.println("Missing or invalid new_password.");
                    return;
                }

                body.updateString("ChallengeResponses.NEW_PASSWORD", input.stringOf("new_password"));
                // requiredAttributes is a JSON array encoded inside a JSON string.
                JsonArray requiredAttributes = new JsonArray();
                String requiredJson = challenge.stringOf("ChallengeParameters.requiredAttributes");
                if (!challenge.hasMember("ChallengeParameters.requiredAttributes")) {
                    requiredJson = "[]";
                }

                try {
                    requiredAttributes.load(requiredJson);
                } catch (ChilkatException e) {
                    System.out.println("Invalid required-attributes list.");
                    return;
                }

                JsonObject answers = new JsonObject();
                try {
                    body.objectOf2("ChallengeResponses", answers);
                } catch (ChilkatException e) {
                    System.out.println("Could not access challenge responses.");
                    return;
                }

                int i = 0;
                int count = requiredAttributes.getSize();
                String attribute = "";
                String attributeValue = "";
                JsonObject supplied = new JsonObject();
                if (count > 0) {
                    try {
                        input.objectOf2("required_attributes", supplied);
                    } catch (ChilkatException e) {
                        System.out.println("Supply all required attributes in required_attributes.");
                        return;
                    }
                }

                while (i < count) {
                    attribute = requiredAttributes.stringAt(i);
                    // Keys are returned as userAttributes.email, userAttributes.name, etc.
                    // StringOf with a quoted path treats the whole key literally.
                    StringBuilder attributePath = new StringBuilder();
                    attributePath.append("\"");
                    attributePath.append(attribute);
                    attributePath.append("\"");
                    attributeValue = supplied.stringOf(attributePath.getAsString());
                    if ((supplied.jsonTypeOf(attributePath.getAsString()) != 1) || ("".equals(attributeValue))) {
                        System.out.println("A required user attribute is missing.");
                        return;
                    }

                    answers.appendString(attribute, attributeValue);
                    i = i + 1;
                }
            } else {
                if ((!"SMS_MFA".equals(challengeName)) && ((!"SOFTWARE_TOKEN_MFA".equals(challengeName)) && (!"EMAIL_OTP".equals(challengeName)))) {
                    System.out.println("This challenge needs a different handler: " + challengeName);
                    // MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
                    return;
                }

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

                if ("SMS_MFA".equals(challengeName)) {
                    body.updateString("ChallengeResponses.SMS_MFA_CODE", input.stringOf("code"));
                }

                if ("SOFTWARE_TOKEN_MFA".equals(challengeName)) {
                    body.updateString("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE", input.stringOf("code"));
                }

                if ("EMAIL_OTP".equals(challengeName)) {
                    body.updateString("ChallengeResponses.EMAIL_OTP_CODE", input.stringOf("code"));
                }
            }

            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.
    }
}