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

Amazon Cognito: Create a User Pool with a Password Policy

See more Amazon Cognito Examples

Live operation: creates an email-verifying, case-insensitive username pool with a password policy, verified-email recovery, and deletion protection. Email is a required attribute, not a configured sign-in alias in this example. Choose required attributes and sign-in configuration carefully: several pool settings cannot be changed after creation.

This focused starting configuration uses Cognito default email delivery, which has low sending limits; configure Amazon SES for production volume. It does not require an SMS role or an existing SES identity. MFA is OFF for this basic example; configure the appropriate MFA method separately. Deletion protection must be disabled deliberately before removing the pool. Creating a pool does not also create an app client or managed-login domain.

Uses the Amazon Cognito User Pools regional JSON API with Chilkat.Rest and AuthAws (Signature Version 4, service cognito-idp). It does not use Identity Pools, the OAuth domain, or a Cognito bearer token. Set the region to match the pool; this example uses the standard AWS commercial endpoint. Other partitions have their own endpoint suffixes.

Supply a private qa_data/aws/cognito.json with string fields access_key, secret_key, and, for temporary IAM/STS credentials, session_token. Prefer short-lived role credentials and refresh them before expiry. The example reads this file explicitly; it does not automatically discover an AWS profile or role. The STS session token is sent in the documented X-Amz-Security-Token query parameter and included in the signature; keep request URLs and diagnostics private. Keep credentials outside public web content and source control. IAM administration can run in a controlled backoffice desktop application or a backend; never embed administrative AWS keys in publicly distributed software.

Required IAM action: cognito-idp:CreateUserPool. This action requires Resource *.

Checks both transport completion and HTTP 200, and validates JSON when response data is expected. AWS error details use __type and message; inspect sensitive diagnostics privately. An HTTP 400 TooManyRequestsException needs bounded exponential backoff with jitter; expired temporary credentials need renewal. Check IAM permission and region for authorization/resource errors. For an uncertain write, inspect the existing resource before retrying. This sample does not automatically retry writes.

AWS CreateUserPool reference

Chilkat Unicode C Downloads

Unicode C
#include <C_CkJsonObjectW.h>
#include <C_CkStringBuilderW.h>
#include <C_CkAuthAwsW.h>
#include <C_CkRestW.h>
#include <C_CkSocketW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJsonObjectW credentials;
    const wchar_t *region;
    HCkStringBuilderW endpoint;
    HCkAuthAwsW aws;
    HCkRestW rest;
    HCkSocketW connection;
    HCkJsonObjectW body;
    HCkJsonObjectW result;
    HCkStringBuilderW requestBody;
    HCkStringBuilderW responseBody;
    const wchar_t *createdPoolId;

    success = FALSE;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = FALSE;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials; these are NOT Cognito app-client credentials or JWTs.
    credentials = CkJsonObjectW_Create();
    CkJsonObjectW_putStrict(credentials,TRUE);
    success = CkJsonObjectW_LoadFile(credentials,L"qa_data/aws/cognito.json");
    if (success != TRUE) {
        wprintf(L"Could not load private AWS credentials.\n");
        CkJsonObjectW_Dispose(credentials);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(credentials,L"access_key") != 1) || (CkJsonObjectW_stringOf(credentials,L"access_key") == L"")) {
        wprintf(L"Missing or invalid access_key.\n");
        CkJsonObjectW_Dispose(credentials);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(credentials,L"secret_key") != 1) || (CkJsonObjectW_stringOf(credentials,L"secret_key") == L"")) {
        wprintf(L"Missing or invalid secret_key.\n");
        CkJsonObjectW_Dispose(credentials);
        return;
    }

    //  Set this once to the region containing the user pool.
    region = L"us-west-2";
    endpoint = CkStringBuilderW_Create();
    CkStringBuilderW_Append(endpoint,L"cognito-idp.");
    CkStringBuilderW_Append(endpoint,region);
    CkStringBuilderW_Append(endpoint,L".amazonaws.com");
    aws = CkAuthAwsW_Create();
    CkAuthAwsW_putAccessKey(aws,CkJsonObjectW_stringOf(credentials,L"access_key"));
    CkAuthAwsW_putSecretKey(aws,CkJsonObjectW_stringOf(credentials,L"secret_key"));
    CkAuthAwsW_putRegion(aws,region);
    CkAuthAwsW_putServiceName(aws,L"cognito-idp");
    CkAuthAwsW_putSignatureVersion(aws,4);
    rest = CkRestW_Create();
    CkRestW_putConnectTimeoutMs(rest,20000);
    CkRestW_putIdleTimeoutMs(rest,60000);
    success = CkRestW_SetAuthAws(rest,aws);
    if (success != TRUE) {
        wprintf(L"Could not configure AWS signing.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        return;
    }

    //  Temporary IAM/STS credentials require their session token on every signed request.
    //  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
    //  Leave session_token absent or empty only for credentials that do not have one.
    if (CkJsonObjectW_HasMember(credentials,L"session_token") == TRUE) {
        if (CkJsonObjectW_JsonTypeOf(credentials,L"session_token") != 1) {
            wprintf(L"session_token must be a string.\n");
            CkJsonObjectW_Dispose(credentials);
            CkStringBuilderW_Dispose(endpoint);
            CkAuthAwsW_Dispose(aws);
            CkRestW_Dispose(rest);
            return;
        }

        if (CkJsonObjectW_stringOf(credentials,L"session_token") != L"") {
            success = CkRestW_AddQueryParam(rest,L"X-Amz-Security-Token",CkJsonObjectW_stringOf(credentials,L"session_token"));
            if (success != TRUE) {
                wprintf(L"Could not set the session-token parameter.\n");
                CkJsonObjectW_Dispose(credentials);
                CkStringBuilderW_Dispose(endpoint);
                CkAuthAwsW_Dispose(aws);
                CkRestW_Dispose(rest);
                return;
            }

        }

    }

    //  Supply a Socket to explicitly enable TLS certificate verification.
    connection = CkSocketW_Create();
    CkSocketW_putRequireSslCertVerify(connection,TRUE);
    CkSocketW_putMaxReadIdleMs(connection,60000);
    CkSocketW_putMaxSendIdleMs(connection,60000);
    success = CkSocketW_Connect(connection,CkStringBuilderW_getAsString(endpoint),443,TRUE,20000);
    if (success != TRUE) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        return;
    }

    success = CkRestW_UseConnection(rest,connection,TRUE);
    if (success != TRUE) {
        wprintf(L"Could not attach the TLS connection.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        return;
    }

    success = CkRestW_AddHeader(rest,L"Content-Type",L"application/x-amz-json-1.0");
    if (success != TRUE) {
        wprintf(L"Could not set the content type.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        return;
    }

    body = CkJsonObjectW_Create();
    result = CkJsonObjectW_Create();
    CkJsonObjectW_putStrict(result,TRUE);
    requestBody = CkStringBuilderW_Create();
    responseBody = CkStringBuilderW_Create();
    success = CkRestW_AddHeader(rest,L"X-Amz-Target",L"AWSCognitoIdentityProviderService.CreateUserPool");
    if (success != TRUE) {
        wprintf(L"Could not set the Cognito operation.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    //  Live operation: creates a new pool. Inspect the result before retrying an uncertain request.
    CkJsonObjectW_UpdateString(body,L"PoolName",L"ExampleUserPool");
    //  Username sign-in, case insensitive; email is required and verified separately.
    CkJsonObjectW_UpdateBool(body,L"UsernameConfiguration.CaseSensitive",FALSE);
    CkJsonObjectW_UpdateString(body,L"Schema[0].Name",L"email");
    CkJsonObjectW_UpdateString(body,L"Schema[0].AttributeDataType",L"String");
    CkJsonObjectW_UpdateBool(body,L"Schema[0].Required",TRUE);
    CkJsonObjectW_UpdateBool(body,L"Schema[0].Mutable",TRUE);
    CkJsonObjectW_UpdateString(body,L"AutoVerifiedAttributes[0]",L"email");
    CkJsonObjectW_UpdateBool(body,L"AdminCreateUserConfig.AllowAdminCreateUserOnly",FALSE);
    CkJsonObjectW_UpdateInt(body,L"Policies.PasswordPolicy.MinimumLength",12);
    CkJsonObjectW_UpdateBool(body,L"Policies.PasswordPolicy.RequireUppercase",TRUE);
    CkJsonObjectW_UpdateBool(body,L"Policies.PasswordPolicy.RequireLowercase",TRUE);
    CkJsonObjectW_UpdateBool(body,L"Policies.PasswordPolicy.RequireNumbers",TRUE);
    CkJsonObjectW_UpdateBool(body,L"Policies.PasswordPolicy.RequireSymbols",TRUE);
    //  This setting belongs under PasswordPolicy, NOT AdminCreateUserConfig.
    CkJsonObjectW_UpdateInt(body,L"Policies.PasswordPolicy.TemporaryPasswordValidityDays",7);
    CkJsonObjectW_UpdateString(body,L"AccountRecoverySetting.RecoveryMechanisms[0].Name",L"verified_email");
    CkJsonObjectW_UpdateInt(body,L"AccountRecoverySetting.RecoveryMechanisms[0].Priority",1);
    CkJsonObjectW_UpdateString(body,L"EmailConfiguration.EmailSendingAccount",L"COGNITO_DEFAULT");
    CkJsonObjectW_UpdateString(body,L"VerificationMessageTemplate.DefaultEmailOption",L"CONFIRM_WITH_CODE");
    CkJsonObjectW_UpdateString(body,L"DeletionProtection",L"ACTIVE");
    //  Basic password demonstration only. Configure MFA separately before production use.
    CkJsonObjectW_UpdateString(body,L"MfaConfiguration",L"OFF");
    //  EmitSb appends, so clear the buffer before each page/request.
    CkStringBuilderW_Clear(requestBody);
    success = CkJsonObjectW_EmitSb(body,requestBody);
    if (success != TRUE) {
        wprintf(L"Could not encode the request.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    //  Chilkat signs this POST, including the current headers and JSON body.
    success = CkRestW_FullRequestSb(rest,L"POST",L"/",requestBody,responseBody);
    if (success != TRUE) {
        //  A failed exchange can leave the outcome of a write unknown. Do not blindly retry it.
        wprintf(L"Request did not complete; inspect LastErrorText privately.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    if (CkRestW_getResponseStatusCode(rest) != 200) {
        wprintf(L"Cognito HTTP status: %d\n",CkRestW_getResponseStatusCode(rest));
        //  AWS commonly reports throttling and expired credentials as HTTP 400, not 429/401.
        success = CkJsonObjectW_LoadSb(result,responseBody);
        if (success == TRUE) {
            wprintf(L"AWS error type: %s\n",CkJsonObjectW_stringOf(result,L"__type"));
            //  Inspect message and response headers privately; they can contain account/user data.
        }

        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    success = CkJsonObjectW_LoadSb(result,responseBody);
    if (success != TRUE) {
        wprintf(L"Expected a well-formed JSON response.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(result,L"UserPool.Id") != 1) || (CkJsonObjectW_stringOf(result,L"UserPool.Id") == L"")) {
        wprintf(L"Missing or invalid UserPool.Id.\n");
        CkJsonObjectW_Dispose(credentials);
        CkStringBuilderW_Dispose(endpoint);
        CkAuthAwsW_Dispose(aws);
        CkRestW_Dispose(rest);
        CkSocketW_Dispose(connection);
        CkJsonObjectW_Dispose(body);
        CkJsonObjectW_Dispose(result);
        CkStringBuilderW_Dispose(requestBody);
        CkStringBuilderW_Dispose(responseBody);
        return;
    }

    createdPoolId = CkJsonObjectW_stringOf(result,L"UserPool.Id");
    wprintf(L"Created pool ID: %s\n",createdPoolId);
    wprintf(L"ARN: %s\n",CkJsonObjectW_stringOf(result,L"UserPool.Arn"));
    //  Save createdPoolId in your application configuration. Create an app client separately.


    CkJsonObjectW_Dispose(credentials);
    CkStringBuilderW_Dispose(endpoint);
    CkAuthAwsW_Dispose(aws);
    CkRestW_Dispose(rest);
    CkSocketW_Dispose(connection);
    CkJsonObjectW_Dispose(body);
    CkJsonObjectW_Dispose(result);
    CkStringBuilderW_Dispose(requestBody);
    CkStringBuilderW_Dispose(responseBody);

    }