Amazon Cognito: List and Filter Users with Pagination
See more Amazon Cognito Examples
Enumerate users in a selected pool with PaginationToken and a page size of 60. Continue while a token is returned, even after a short or empty page. The example prints username, status, enabled state, and the stable sub identifier without dumping email/phone attributes. Stops explicitly at 1000 pages.
ListUsers is eventually consistent; use AdminGetUser to check a specific user. Its server-side filter supports one supported standard attribute at a time, using exact (=) or prefix (^=) matching. Custom attributes are not searchable. The optional userFilter expression is encoded by JsonObject, including embedded quotes. Omitting AttributesToGet avoids errors caused by requesting an attribute absent on some matching users. Save the pool ID with each user sub.
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:ListUsers. Scope access to the intended user-pool ARN.
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.
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = 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.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/cognito.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load private AWS credentials." & @CRLF)
Exit
EndIf
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($oCredentials.StringOf("access_key") = "")) Then
ConsoleWrite("Missing or invalid access_key." & @CRLF)
Exit
EndIf
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($oCredentials.StringOf("secret_key") = "")) Then
ConsoleWrite("Missing or invalid secret_key." & @CRLF)
Exit
EndIf
; Set this once to the region containing the user pool.
Local $sRegion = "us-west-2"
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("cognito-idp.")
$oEndpoint.Append($sRegion)
$oEndpoint.Append(".amazonaws.com")
$oAws = ObjCreate("Chilkat.AuthAws")
$oAws.AccessKey = $oCredentials.StringOf("access_key")
$oAws.SecretKey = $oCredentials.StringOf("secret_key")
$oAws.Region = $sRegion
$oAws.ServiceName = "cognito-idp"
$oAws.SignatureVersion = 4
$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
$bSuccess = $oRest.SetAuthAws($oAws)
If ($bSuccess <> True) Then
ConsoleWrite("Could not configure AWS signing." & @CRLF)
Exit
EndIf
; 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 ($oCredentials.HasMember("session_token") = True) Then
If ($oCredentials.JsonTypeOf("session_token") <> 1) Then
ConsoleWrite("session_token must be a string." & @CRLF)
Exit
EndIf
If ($oCredentials.StringOf("session_token") <> "") Then
$bSuccess = $oRest.AddQueryParam("X-Amz-Security-Token",$oCredentials.StringOf("session_token"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not set the session-token parameter." & @CRLF)
Exit
EndIf
EndIf
EndIf
; Supply a Socket to explicitly enable TLS certificate verification.
$oConnection = ObjCreate("Chilkat.Socket")
$oConnection.RequireSslCertVerify = True
$oConnection.MaxReadIdleMs = 60000
$oConnection.MaxSendIdleMs = 60000
$bSuccess = $oConnection.Connect($oEndpoint.GetAsString(),443,True,20000)
If ($bSuccess <> True) Then
ConsoleWrite("TLS connection failed; inspect diagnostics privately." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.UseConnection($oConnection,True)
If ($bSuccess <> True) Then
ConsoleWrite("Could not attach the TLS connection." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddHeader("Content-Type","application/x-amz-json-1.0")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set the content type." & @CRLF)
Exit
EndIf
$oBody = ObjCreate("Chilkat.JsonObject")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oRequestBody = ObjCreate("Chilkat.StringBuilder")
$oResponseBody = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oRest.AddHeader("X-Amz-Target","AWSCognitoIdentityProviderService.ListUsers")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set the Cognito operation." & @CRLF)
Exit
EndIf
Local $sUserPoolId = "us-west-2_EXAMPLE"
$oBody.UpdateString("UserPoolId",$sUserPoolId)
$oBody.UpdateInt("Limit",60)
; Optional filter expression, for example: email = "user@example.com"
; Leave empty to list all users. JsonObject handles JSON escaping.
Local $sUserFilter = ""
If ($sUserFilter <> "") Then
$oBody.UpdateString("Filter",$sUserFilter)
EndIf
Local $iJ = 0
Local $iAttributeCount = 0
; Page size is not a total-result limit. Continue even after an empty page.
Local $sNextToken = ""
Local $bMore = True
Local $iPage = 0
Local $i = 0
Local $iCount = 0
$oSeenTokens = ObjCreate("Chilkat.Hashtable")
While ($bMore = True)
; Demonstration bound: report partial results instead of silently truncating.
If ($iPage = 1000) Then
ConsoleWrite("Stopped at 1000 pages; enumeration is incomplete. Resume with nextToken." & @CRLF)
Exit
EndIf
; EmitSb appends, so clear the buffer before each page/request.
$oRequestBody.Clear
$bSuccess = $oBody.EmitSb($oRequestBody)
If ($bSuccess <> True) Then
ConsoleWrite("Could not encode the request." & @CRLF)
Exit
EndIf
; Chilkat signs this POST, including the current headers and JSON body.
$bSuccess = $oRest.FullRequestSb("POST","/",$oRequestBody,$oResponseBody)
If ($bSuccess <> True) Then
; A failed exchange can leave the outcome of a write unknown. Do not blindly retry it.
ConsoleWrite("Request did not complete; inspect LastErrorText privately." & @CRLF)
Exit
EndIf
If ($oRest.ResponseStatusCode <> 200) Then
ConsoleWrite("Cognito HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
; AWS commonly reports throttling and expired credentials as HTTP 400, not 429/401.
$bSuccess = $oResult.LoadSb($oResponseBody)
If ($bSuccess = True) Then
ConsoleWrite("AWS error type: " & $oResult.StringOf("__type") & @CRLF)
; Inspect message and response headers privately; they can contain account/user data.
EndIf
Exit
EndIf
$bSuccess = $oResult.LoadSb($oResponseBody)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("Users") <> 4) Then
ConsoleWrite("Expected Users array." & @CRLF)
Exit
EndIf
$iCount = $oResult.SizeOfArray("Users")
$i = 0
While $i < $iCount
$oResult.I = $i
If (($oResult.JsonTypeOf("Users[i].Username") <> 1) Or ($oResult.StringOf("Users[i].Username") = "")) Then
ConsoleWrite("Missing or invalid Users[i].Username." & @CRLF)
Exit
EndIf
ConsoleWrite("Username: " & $oResult.StringOf("Users[i].Username") & @CRLF)
ConsoleWrite("Status: " & $oResult.StringOf("Users[i].UserStatus") & @CRLF)
ConsoleWrite("Enabled: " & $oResult.BoolOf("Users[i].Enabled") & @CRLF)
; Attributes are a name/value array, not an object keyed by attribute name.
$iJ = 0
$iAttributeCount = $oResult.SizeOfArray("Users[i].Attributes")
While $iJ < $iAttributeCount
$oResult.J = $iJ
If ($oResult.StringOf("Users[i].Attributes[j].Name") = "sub") Then
ConsoleWrite("User sub: " & $oResult.StringOf("Users[i].Attributes[j].Value") & @CRLF)
EndIf
$iJ = $iJ + 1
Wend
$i = $i + 1
Wend
$iPage = $iPage + 1
$bMore = False
If ($oResult.HasMember("PaginationToken") = True) Then
If ($oResult.JsonTypeOf("PaginationToken") <> 6) Then
If (($oResult.JsonTypeOf("PaginationToken") <> 1) Or ($oResult.StringOf("PaginationToken") = "")) Then
ConsoleWrite("Missing or invalid PaginationToken." & @CRLF)
Exit
EndIf
$sNextToken = $oResult.StringOf("PaginationToken")
If ($oSeenTokens.Contains($sNextToken) = True) Then
ConsoleWrite("Repeated pagination token; enumeration is incomplete." & @CRLF)
Exit
EndIf
$oSeenTokens.AddInt($sNextToken,1)
$oBody.UpdateString("PaginationToken",$sNextToken)
$bMore = True
EndIf
EndIf
Wend
ConsoleWrite("Enumeration complete." & @CRLF)