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

Amazon Cognito: Sign In with Managed Login and PKCE

See more Amazon Cognito Examples

Configure a User Pool domain and a public app client with no secret. Enable the authorization-code grant, the Cognito identity provider (or your configured IdP), and the requested openid, email, and aws.cognito.signin.user.admin scopes. Register http://localhost:3017/ exactly as an allowed callback URL. Chilkat receives the local callback and manages state and S256 PKCE; no hosted callback service is needed. Use the system browser, not a password form embedded in your application.

The self-service admin scope permits user operations such as TOTP enrollment; it does not grant IAM administration. Cognito code flow returns refresh tokens without offline_access. A public desktop client must not contain a client secret. Web/mobile applications need their own appropriate callback handling. Tokens are saved privately; decoding their claims is not validation.

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.JsonObject;
import com.chilkatsoft.chilkat2.OAuth2;
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/");
        if ((app.jsonTypeOf("domain") != 1) || ("".equals(app.stringOf("domain")))) {
            System.out.println("Missing or invalid domain.");
            return;
        }

        // This URL comes from trusted configuration, never from a token or user-supplied URL.
        StringBuilder tokenEndpoint = new StringBuilder();
        tokenEndpoint.append(app.stringOf("domain"));
        tokenEndpoint.append("/oauth2/token");
        OAuth2 oauth = new OAuth2();
        StringBuilder authorizeEndpoint = new StringBuilder();
        authorizeEndpoint.append(app.stringOf("domain"));
        authorizeEndpoint.append("/oauth2/authorize");
        oauth.setAuthorizationEndpoint(authorizeEndpoint.getAsString());
        oauth.setTokenEndpoint(tokenEndpoint.getAsString());
        oauth.setClientId(clientId);
        // Register exactly http://localhost:3017/ as an allowed callback for this public client.
        oauth.setLocalHost("localhost");
        oauth.setListenPort(3017);
        oauth.setCodeChallenge(true);
        oauth.setCodeChallengeMethod("S256");
        // Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
        oauth.setScope("openid email aws.cognito.signin.user.admin");
        String authUrl;
        try {
            authUrl = oauth.startAuth();
        } catch (ChilkatException e) {
            System.out.println("Could not start the local OAuth listener.");
            return;
        }

        try {
            oauth.launchBrowser(authUrl);
        } catch (ChilkatException e) {
            oauth.cancel();
            System.out.println("Could not launch the system browser.");
            return;
        }

        int waited = 0;
        while ((oauth.getAuthFlowState() < 3) && (waited < 180000)) {
            oauth.sleepMs(200);
            waited = waited + 200;
        }

        if (oauth.getAuthFlowState() < 3) {
            oauth.cancel();
            System.out.println("Authorization timed out.");
            return;
        }

        if (oauth.getAuthFlowState() != 3) {
            System.out.println("Authorization did not complete.");
            return;
        }

        JsonObject token = new JsonObject();
        token.setStrict(true);
        try {
            token.load(oauth.getAccessTokenResponse());
        } catch (ChilkatException e) {
            System.out.println("Could not parse the token response.");
            return;
        }

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

        System.out.println("Authorization completed; private token cache saved.");
        // Validate JWT signatures and claims before trusting their contents:
        // Validate a Cognito JWT.
    }
}