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

Amazon Cognito: Add, List, or Remove Group Memberships

See more Amazon Cognito Examples

Choose list, add, or remove for an existing user and existing group. List follows NextToken, including empty pages, and reports an explicit stop at the 1000-page demonstration bound. It lists this user's groups, not every group or member in the pool. Adding/removing membership requires cognito-idp:AdminAddUserToGroup or AdminRemoveUserFromGroup; listing requires AdminListGroupsForUser. Scope IAM access to the pool ARN.

Live change: membership can affect application authorization and Identity Pool role selection. Existing JWT claims do not change in place; newly issued tokens reflect current membership. Groups do not themselves grant arbitrary AWS permissions; Identity Pool role mappings and IAM policies determine AWS access.

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.

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 CkPerl Downloads

CkPerl
use chilkat();

$success = 0;

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
#  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 = chilkat::CkJsonObject->new();
$credentials->put_Strict(1);
$success = $credentials->LoadFile("qa_data/aws/cognito.json");
if ($success != 1) {
    print "Could not load private AWS credentials." . "\r\n";
    exit;
}

if (($credentials->JsonTypeOf("access_key") != 1) or ($credentials->stringOf("access_key") == "")) {
    print "Missing or invalid access_key." . "\r\n";
    exit;
}

if (($credentials->JsonTypeOf("secret_key") != 1) or ($credentials->stringOf("secret_key") == "")) {
    print "Missing or invalid secret_key." . "\r\n";
    exit;
}

#  Set this once to the region containing the user pool.
$region = "us-west-2";
$endpoint = chilkat::CkStringBuilder->new();
$endpoint->Append("cognito-idp.");
$endpoint->Append($region);
$endpoint->Append(".amazonaws.com");
$aws = chilkat::CkAuthAws->new();
$aws->put_AccessKey($credentials->stringOf("access_key"));
$aws->put_SecretKey($credentials->stringOf("secret_key"));
$aws->put_Region($region);
$aws->put_ServiceName("cognito-idp");
$aws->put_SignatureVersion(4);
$rest = chilkat::CkRest->new();
$rest->put_ConnectTimeoutMs(20000);
$rest->put_IdleTimeoutMs(60000);
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
    print "Could not configure AWS signing." . "\r\n";
    exit;
}

#  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 ($credentials->HasMember("session_token") == 1) {
    if ($credentials->JsonTypeOf("session_token") != 1) {
        print "session_token must be a string." . "\r\n";
        exit;
    }

    if ($credentials->stringOf("session_token") != "") {
        $success = $rest->AddQueryParam("X-Amz-Security-Token",$credentials->stringOf("session_token"));
        if ($success != 1) {
            print "Could not set the session-token parameter." . "\r\n";
            exit;
        }

    }

}

#  Supply a Socket to explicitly enable TLS certificate verification.
$connection = chilkat::CkSocket->new();
$connection->put_RequireSslCertVerify(1);
$connection->put_MaxReadIdleMs(60000);
$connection->put_MaxSendIdleMs(60000);
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
    print "TLS connection failed; inspect diagnostics privately." . "\r\n";
    exit;
}

$success = $rest->UseConnection($connection,1);
if ($success != 1) {
    print "Could not attach the TLS connection." . "\r\n";
    exit;
}

$success = $rest->AddHeader("Content-Type","application/x-amz-json-1.0");
if ($success != 1) {
    print "Could not set the content type." . "\r\n";
    exit;
}

$body = chilkat::CkJsonObject->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
$requestBody = chilkat::CkStringBuilder->new();
$responseBody = chilkat::CkStringBuilder->new();
$userPoolId = "us-west-2_EXAMPLE";
$body->UpdateString("UserPoolId",$userPoolId);
#  Use the returned Cognito Username, not an assumed email alias.
$username = "example-user";
$body->UpdateString("Username",$username);
$action = "list";
$groupName = "ExampleGroup";
if (($action != "list") and ($action != "add") and ($action != "remove")) {
    print "Choose list, add, or remove." . "\r\n";
    exit;
}

if ($action != "list") {
    $body->UpdateString("GroupName",$groupName);
    $operation = "AWSCognitoIdentityProviderService.AdminAddUserToGroup";
    if ($action == "remove") {
        $operation = "AWSCognitoIdentityProviderService.AdminRemoveUserFromGroup";
    }

    $success = $rest->AddHeader("X-Amz-Target",$operation);
    if ($success != 1) {
        print "Could not select the membership operation." . "\r\n";
        exit;
    }

    #  EmitSb appends, so clear the buffer before each page/request.
    $requestBody->Clear();
    $success = $body->EmitSb($requestBody);
    if ($success != 1) {
        print "Could not encode the request." . "\r\n";
        exit;
    }

    #  Chilkat signs this POST, including the current headers and JSON body.
    $success = $rest->FullRequestSb("POST","/",$requestBody,$responseBody);
    if ($success != 1) {
        #  A failed exchange can leave the outcome of a write unknown. Do not blindly retry it.
        print "Request did not complete; inspect LastErrorText privately." . "\r\n";
        exit;
    }

    if ($rest->get_ResponseStatusCode() != 200) {
        print "Cognito HTTP status: " . $rest->get_ResponseStatusCode() . "\r\n";
        #  AWS commonly reports throttling and expired credentials as HTTP 400, not 429/401.
        $success = $result->LoadSb($responseBody);
        if ($success == 1) {
            print "AWS error type: " . $result->stringOf("__type") . "\r\n";
            #  Inspect message and response headers privately; they can contain account/user data.
        }

        exit;
    }

    print "Membership change accepted." . "\r\n";
    exit;
}

$success = $rest->AddHeader("X-Amz-Target","AWSCognitoIdentityProviderService.AdminListGroupsForUser");
if ($success != 1) {
    print "Could not set the Cognito operation." . "\r\n";
    exit;
}

$body->UpdateInt("Limit",60);
#  Page size is not a total-result limit. Continue even after an empty page.
$nextToken = "";
$more = 1;
$page = 0;
$i = 0;
$count = 0;
$seenTokens = chilkat::CkHashtable->new();
while (($more == 1)) {
    #  Demonstration bound: report partial results instead of silently truncating.
    if ($page == 1000) {
        print "Stopped at 1000 pages; enumeration is incomplete. Resume with nextToken." . "\r\n";
        exit;
    }

    #  EmitSb appends, so clear the buffer before each page/request.
    $requestBody->Clear();
    $success = $body->EmitSb($requestBody);
    if ($success != 1) {
        print "Could not encode the request." . "\r\n";
        exit;
    }

    #  Chilkat signs this POST, including the current headers and JSON body.
    $success = $rest->FullRequestSb("POST","/",$requestBody,$responseBody);
    if ($success != 1) {
        #  A failed exchange can leave the outcome of a write unknown. Do not blindly retry it.
        print "Request did not complete; inspect LastErrorText privately." . "\r\n";
        exit;
    }

    if ($rest->get_ResponseStatusCode() != 200) {
        print "Cognito HTTP status: " . $rest->get_ResponseStatusCode() . "\r\n";
        #  AWS commonly reports throttling and expired credentials as HTTP 400, not 429/401.
        $success = $result->LoadSb($responseBody);
        if ($success == 1) {
            print "AWS error type: " . $result->stringOf("__type") . "\r\n";
            #  Inspect message and response headers privately; they can contain account/user data.
        }

        exit;
    }

    $success = $result->LoadSb($responseBody);
    if ($success != 1) {
        print "Expected a well-formed JSON response." . "\r\n";
        exit;
    }

    if ($result->JsonTypeOf("Groups") != 4) {
        print "Expected Groups array." . "\r\n";
        exit;
    }

    $count = $result->SizeOfArray("Groups");
    $i = 0;
    while ($i < $count) {
        $result->put_I($i);
        if (($result->JsonTypeOf("Groups[i].GroupName") != 1) or ($result->stringOf("Groups[i].GroupName") == "")) {
            print "Missing or invalid Groups[i].GroupName." . "\r\n";
            exit;
        }

        print "Group: " . $result->stringOf("Groups[i].GroupName") . "\r\n";
        print "Role ARN: " . $result->stringOf("Groups[i].RoleArn") . "\r\n";
        $i = $i + 1;
    }

    $page = $page + 1;
    $more = 0;
    if ($result->HasMember("NextToken") == 1) {
        if ($result->JsonTypeOf("NextToken") != 6) {
            if (($result->JsonTypeOf("NextToken") != 1) or ($result->stringOf("NextToken") == "")) {
                print "Missing or invalid NextToken." . "\r\n";
                exit;
            }

            $nextToken = $result->stringOf("NextToken");
            if ($seenTokens->Contains($nextToken) == 1) {
                print "Repeated pagination token; enumeration is incomplete." . "\r\n";
                exit;
            }

            $seenTokens->AddInt($nextToken,1);
            $body->UpdateString("NextToken",$nextToken);
            $more = 1;
        }

    }

}

print "Enumeration complete." . "\r\n";