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

C
#include <C_CkJsonObject.h>
#include <C_CkStringBuilder.h>
#include <C_CkOAuth2.h>
#include <C_CkDateTime.h>
#include <C_CkFileAccess.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJsonObject app;
    const char *clientId;
    HCkStringBuilder endpoint;
    HCkStringBuilder tokenEndpoint;
    HCkOAuth2 oauth;
    HCkStringBuilder authorizeEndpoint;
    const char *authUrl;
    int waited;
    HCkJsonObject token;
    HCkDateTime obtained;
    HCkFileAccess tokenusertokens;

    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.
    app = CkJsonObject_Create();
    CkJsonObject_putStrict(app,TRUE);
    success = CkJsonObject_LoadFile(app,"qa_data/cognito/app.json");
    if (success != TRUE) {
        printf("Could not load Cognito app settings.\n");
        CkJsonObject_Dispose(app);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(app,"region") != 1) || (CkJsonObject_stringOf(app,"region") == "")) {
        printf("Missing or invalid region.\n");
        CkJsonObject_Dispose(app);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(app,"user_pool_id") != 1) || (CkJsonObject_stringOf(app,"user_pool_id") == "")) {
        printf("Missing or invalid user_pool_id.\n");
        CkJsonObject_Dispose(app);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(app,"client_id") != 1) || (CkJsonObject_stringOf(app,"client_id") == "")) {
        printf("Missing or invalid client_id.\n");
        CkJsonObject_Dispose(app);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(app,"account_key") != 1) || (CkJsonObject_stringOf(app,"account_key") == "")) {
        printf("Missing or invalid account_key.\n");
        CkJsonObject_Dispose(app);
        return;
    }

    clientId = CkJsonObject_stringOf(app,"client_id");
    endpoint = CkStringBuilder_Create();
    CkStringBuilder_Append(endpoint,"https://cognito-idp.");
    CkStringBuilder_Append(endpoint,CkJsonObject_stringOf(app,"region"));
    CkStringBuilder_Append(endpoint,".amazonaws.com/");
    if ((CkJsonObject_JsonTypeOf(app,"domain") != 1) || (CkJsonObject_stringOf(app,"domain") == "")) {
        printf("Missing or invalid domain.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        return;
    }

    //  This URL comes from trusted configuration, never from a token or user-supplied URL.
    tokenEndpoint = CkStringBuilder_Create();
    CkStringBuilder_Append(tokenEndpoint,CkJsonObject_stringOf(app,"domain"));
    CkStringBuilder_Append(tokenEndpoint,"/oauth2/token");
    oauth = CkOAuth2_Create();
    authorizeEndpoint = CkStringBuilder_Create();
    CkStringBuilder_Append(authorizeEndpoint,CkJsonObject_stringOf(app,"domain"));
    CkStringBuilder_Append(authorizeEndpoint,"/oauth2/authorize");
    CkOAuth2_putAuthorizationEndpoint(oauth,CkStringBuilder_getAsString(authorizeEndpoint));
    CkOAuth2_putTokenEndpoint(oauth,CkStringBuilder_getAsString(tokenEndpoint));
    CkOAuth2_putClientId(oauth,clientId);
    //  Register exactly http://localhost:3017/ as an allowed callback for this public client.
    CkOAuth2_putLocalHost(oauth,"localhost");
    CkOAuth2_putListenPort(oauth,3017);
    CkOAuth2_putCodeChallenge(oauth,TRUE);
    CkOAuth2_putCodeChallengeMethod(oauth,"S256");
    //  Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
    CkOAuth2_putScope(oauth,"openid email aws.cognito.signin.user.admin");
    authUrl = CkOAuth2_startAuth(oauth);
    if (CkOAuth2_getLastMethodSuccess(oauth) != TRUE) {
        printf("Could not start the local OAuth listener.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        return;
    }

    success = CkOAuth2_LaunchBrowser(oauth,authUrl);
    if (success != TRUE) {
        CkOAuth2_Cancel(oauth);
        printf("Could not launch the system browser.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        return;
    }

    waited = 0;
    while (((CkOAuth2_getAuthFlowState(oauth) < 3) && (waited < 180000))) {
        CkOAuth2_SleepMs(oauth,200);
        waited = waited + 200;
    }

    if (CkOAuth2_getAuthFlowState(oauth) < 3) {
        CkOAuth2_Cancel(oauth);
        printf("Authorization timed out.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        return;
    }

    if (CkOAuth2_getAuthFlowState(oauth) != 3) {
        printf("Authorization did not complete.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        return;
    }

    token = CkJsonObject_Create();
    CkJsonObject_putStrict(token,TRUE);
    success = CkJsonObject_Load(token,CkOAuth2_accessTokenResponse(oauth));
    if (success != TRUE) {
        printf("Could not parse the token response.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"access_token") != 1) || (CkJsonObject_stringOf(token,"access_token") == "")) {
        printf("Missing or invalid access_token.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"id_token") != 1) || (CkJsonObject_stringOf(token,"id_token") == "")) {
        printf("Missing or invalid id_token.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"expires_in") != 2) || (CkJsonObject_IntOf(token,"expires_in") <= 0)) {
        printf("Expected a positive token lifetime.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    if (CkJsonObject_stringOf(token,"token_type") != "Bearer") {
        printf("Expected Bearer tokens.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"refresh_token") != 1) || (CkJsonObject_stringOf(token,"refresh_token") == "")) {
        printf("Missing or invalid refresh_token.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        return;
    }

    CkJsonObject_UpdateString(token,"client_id",CkJsonObject_stringOf(app,"client_id"));
    CkJsonObject_UpdateString(token,"user_pool_id",CkJsonObject_stringOf(app,"user_pool_id"));
    CkJsonObject_UpdateString(token,"account_key",CkJsonObject_stringOf(app,"account_key"));
    obtained = CkDateTime_Create();
    success = CkDateTime_SetFromCurrentSystemTime(obtained);
    if (success != TRUE) {
        printf("Could not get the acquisition time.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        CkDateTime_Dispose(obtained);
        return;
    }

    CkJsonObject_UpdateString(token,"obtained_at",CkDateTime_getAsTimestamp(obtained,FALSE));
    tokenusertokens = CkFileAccess_Create();
    success = CkFileAccess_DirEnsureExists(tokenusertokens,"qa_data/tokens");
    if (success != TRUE) {
        printf("Could not create the private cache directory.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        CkDateTime_Dispose(obtained);
        CkFileAccess_Dispose(tokenusertokens);
        return;
    }

    if (CkFileAccess_FileExists(tokenusertokens,"qa_data/tokens/cognito-user.json") == TRUE) {
        success = CkFileAccess_FileCopy(tokenusertokens,"qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",FALSE);
        if (success != TRUE) {
            printf("Could not back up the existing cache.\n");
            CkJsonObject_Dispose(app);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(tokenEndpoint);
            CkOAuth2_Dispose(oauth);
            CkStringBuilder_Dispose(authorizeEndpoint);
            CkJsonObject_Dispose(token);
            CkDateTime_Dispose(obtained);
            CkFileAccess_Dispose(tokenusertokens);
            return;
        }

    }

    success = CkJsonObject_WriteFile(token,"qa_data/tokens/cognito-user.json");
    if (success != TRUE) {
        printf("Could not save user tokens; preserve any previous backup.\n");
        CkJsonObject_Dispose(app);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(tokenEndpoint);
        CkOAuth2_Dispose(oauth);
        CkStringBuilder_Dispose(authorizeEndpoint);
        CkJsonObject_Dispose(token);
        CkDateTime_Dispose(obtained);
        CkFileAccess_Dispose(tokenusertokens);
        return;
    }

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


    CkJsonObject_Dispose(app);
    CkStringBuilder_Dispose(endpoint);
    CkStringBuilder_Dispose(tokenEndpoint);
    CkOAuth2_Dispose(oauth);
    CkStringBuilder_Dispose(authorizeEndpoint);
    CkJsonObject_Dispose(token);
    CkDateTime_Dispose(obtained);
    CkFileAccess_Dispose(tokenusertokens);

    }