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

Amazon Cognito: Create a User and Send an Email Invitation

See more Amazon Cognito Examples

Live email: create an administrator-invited user in a password-based pool and request EMAIL delivery. Replace the recipient deliberately and supply all required pool attributes. With TemporaryPassword omitted, Cognito generates it for this password-based flow. Passwordless pools have different omission behavior. The invitation template must include the password placeholder {####}; email delivery configuration and limits must also permit sending.

A password-based invited user normally has status FORCE_CHANGE_PASSWORD and must complete the NEW_PASSWORD_REQUIRED challenge at sign-in. A successful creation response does not prove delivery to the inbox. MessageAction=SUPPRESS creates without sending an invitation, but you must arrange onboarding. MessageAction=RESEND resends an invitation and resets the temporary-password duration. ForceAliasCreation is false to avoid moving a verified alias from another user. Creating a user does not prove ownership of its email address.

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:AdminCreateUser. 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.

AWS AdminCreateUser reference

Chilkat AutoIt Downloads

AutoIt
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.AdminCreateUser")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set the Cognito operation." & @CRLF)
    Exit
EndIf

Local $sUserPoolId = "us-west-2_EXAMPLE"
$oBody.UpdateString("UserPoolId",$sUserPoolId)
;  Use the returned Cognito Username, not an assumed email alias.
Local $sUsername = "example-user"
$oBody.UpdateString("Username",$sUsername)
;  Live operation: sends an EMAIL invitation. Use a real intended recipient.
;  For a password-based pool, Cognito generates the temporary password when omitted.
$oBody.UpdateString("DesiredDeliveryMediums[0]","EMAIL")
$oBody.UpdateString("UserAttributes[0].Name","email")
$oBody.UpdateString("UserAttributes[0].Value","user@example.com")
$oBody.UpdateBool("ForceAliasCreation",False)
;  Do not set email_verified=true without independently establishing email ownership.
;  Add any other attributes required by your pool schema before sending.
;  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("User.Username") <> 1) Or ($oResult.StringOf("User.Username") = "")) Then
    ConsoleWrite("Missing or invalid User.Username." & @CRLF)
    Exit
EndIf

ConsoleWrite("Created username: " & $oResult.StringOf("User.Username") & @CRLF)
ConsoleWrite("Status: " & $oResult.StringOf("User.UserStatus") & @CRLF)
Local $i = 0
Local $iCount = $oResult.SizeOfArray("User.Attributes")
While $i < $iCount
    $oResult.I = $i
    If ($oResult.StringOf("User.Attributes[i].Name") = "sub") Then
        ConsoleWrite("User sub: " & $oResult.StringOf("User.Attributes[i].Value") & @CRLF)
    EndIf

    $i = $i + 1
Wend