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

Amazon Cognito: Register and Confirm a User

See more Amazon Cognito Examples

Choose signup, confirm, or resend. A private signup-input.json supplies username, password and email for signup, or username and code for confirmation. Confirmation is a later user action; do not reuse a placeholder code or automatically confirm the user as an administrator. Resend requests another delivery. Self-registration must be enabled, and this password-based example must supply all required schema attributes.

Live operation: creates an account and can send email/SMS. Confirmation can establish a verified alias, so ForceAliasCreation=false prevents moving an existing alias from someone else. SignUp can return LimitExceeded even after creating an UNCONFIRMED user; investigate/resend rather than repeatedly creating accounts. Successful submission does not prove inbox delivery.

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 Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.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/");
    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    CkHttpResponseW resp;
    CkJsonObjectW body;
    CkJsonObjectW result;
    result.put_Strict(true);
    //  Run one step per invocation; collect a real code from the recipient before "confirm".
    const wchar_t *action = L"signup";
    if ((action != L"signup") && (action != L"confirm") && (action != L"resend")) {
        wprintf(L"Choose signup, confirm, or resend.\n");
        return;
    }

    CkJsonObjectW input;
    input.put_Strict(true);
    success = input.LoadFile(L"qa_data/cognito/signup-input.json");
    if (success != true) {
        wprintf(L"Could not load qa_data/cognito/signup-input.json.\n");
        return;
    }

    if ((input.JsonTypeOf(L"username") != 1) || (input.stringOf(L"username") == L"")) {
        wprintf(L"Missing or invalid username.\n");
        return;
    }

    body.UpdateString(L"ClientId",clientId);
    body.UpdateString(L"Username",input.stringOf(L"username"));
    if (action == L"signup") {
        if ((input.JsonTypeOf(L"password") != 1) || (input.stringOf(L"password") == L"")) {
            wprintf(L"Missing or invalid password.\n");
            return;
        }

        if ((input.JsonTypeOf(L"email") != 1) || (input.stringOf(L"email") == L"")) {
            wprintf(L"Missing or invalid email.\n");
            return;
        }

        body.UpdateString(L"Password",input.stringOf(L"password"));
        body.UpdateString(L"UserAttributes[0].Name",L"email");
        body.UpdateString(L"UserAttributes[0].Value",input.stringOf(L"email"));
        //  Add any additional attributes required by your pool before sending.
        http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.SignUp");
        success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
        if (resp.get_StatusCode() != 200) {
            wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
            success = result.Load(resp.bodyStr());
            if (success == true) {
                wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
                wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
            }

            //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
            return;
        }

        if (success != true) {
            wprintf(L"The HTTP exchange did not complete.\n");
            return;
        }

        success = result.Load(resp.bodyStr());
        if (success != true) {
            wprintf(L"Expected a JSON response.\n");
            return;
        }

        if ((result.JsonTypeOf(L"UserSub") != 1) || (result.stringOf(L"UserSub") == L"")) {
            wprintf(L"Missing or invalid UserSub.\n");
            return;
        }

        wprintf(L"User sub: %s\n",result.stringOf(L"UserSub"));
        wprintf(L"Confirmed: %d\n",result.BoolOf(L"UserConfirmed"));
        wprintf(L"Delivery medium: %s\n",result.stringOf(L"CodeDeliveryDetails.DeliveryMedium"));
    }

    if (action == L"confirm") {
        if ((input.JsonTypeOf(L"code") != 1) || (input.stringOf(L"code") == L"")) {
            wprintf(L"Missing or invalid code.\n");
            return;
        }

        body.UpdateString(L"ConfirmationCode",input.stringOf(L"code"));
        body.UpdateBool(L"ForceAliasCreation",false);
        http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.ConfirmSignUp");
        success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
        if (resp.get_StatusCode() != 200) {
            wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
            success = result.Load(resp.bodyStr());
            if (success == true) {
                wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
                wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
            }

            //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
            return;
        }

        if (success != true) {
            wprintf(L"The HTTP exchange did not complete.\n");
            return;
        }

        wprintf(L"Registration confirmed. The user can now sign in.\n");
    }

    if (action == L"resend") {
        http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.ResendConfirmationCode");
        success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
        if (resp.get_StatusCode() != 200) {
            wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
            success = result.Load(resp.bodyStr());
            if (success == true) {
                wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
                wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
            }

            //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
            return;
        }

        if (success != true) {
            wprintf(L"The HTTP exchange did not complete.\n");
            return;
        }

        success = result.Load(resp.bodyStr());
        if (success != true) {
            wprintf(L"Expected a JSON response.\n");
            return;
        }

        wprintf(L"Confirmation code requested; use the most recent code.\n");
    }
    }