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

Unicode C++
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkOAuth2W.h>
#include <CkDateTimeW.h>
#include <CkFileAccessW.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/");
    if ((app.JsonTypeOf(L"domain") != 1) || (app.stringOf(L"domain") == L"")) {
        wprintf(L"Missing or invalid domain.\n");
        return;
    }

    //  This URL comes from trusted configuration, never from a token or user-supplied URL.
    CkStringBuilderW tokenEndpoint;
    tokenEndpoint.Append(app.stringOf(L"domain"));
    tokenEndpoint.Append(L"/oauth2/token");
    CkOAuth2W oauth;
    CkStringBuilderW authorizeEndpoint;
    authorizeEndpoint.Append(app.stringOf(L"domain"));
    authorizeEndpoint.Append(L"/oauth2/authorize");
    oauth.put_AuthorizationEndpoint(authorizeEndpoint.getAsString());
    oauth.put_TokenEndpoint(tokenEndpoint.getAsString());
    oauth.put_ClientId(clientId);
    //  Register exactly http://localhost:3017/ as an allowed callback for this public client.
    oauth.put_LocalHost(L"localhost");
    oauth.put_ListenPort(3017);
    oauth.put_CodeChallenge(true);
    oauth.put_CodeChallengeMethod(L"S256");
    //  Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
    oauth.put_Scope(L"openid email aws.cognito.signin.user.admin");
    const wchar_t *authUrl = oauth.startAuth();
    if (oauth.get_LastMethodSuccess() != true) {
        wprintf(L"Could not start the local OAuth listener.\n");
        return;
    }

    success = oauth.LaunchBrowser(authUrl);
    if (success != true) {
        oauth.Cancel();
        wprintf(L"Could not launch the system browser.\n");
        return;
    }

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

    if (oauth.get_AuthFlowState() < 3) {
        oauth.Cancel();
        wprintf(L"Authorization timed out.\n");
        return;
    }

    if (oauth.get_AuthFlowState() != 3) {
        wprintf(L"Authorization did not complete.\n");
        return;
    }

    CkJsonObjectW token;
    token.put_Strict(true);
    success = token.Load(oauth.accessTokenResponse());
    if (success != true) {
        wprintf(L"Could not parse the token response.\n");
        return;
    }

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

    wprintf(L"Authorization completed; private token cache saved.\n");
    //  Validate JWT signatures and claims before trusting their contents:
    //  Validate a Cognito JWT.
    }