How can you programmatically create a user in a Cognito User Pool?

Question:

The AWS documentation indicates that it is possible for an admin to create a user pool user in AWS Cognito using the API.

Here is the documentation I am referring to: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html

However the documentation provides scant details and not even an example of how this is done. It makes no mention of what endpoint to call, what SDK function to use, or anything regarding authentication, etc.

Does anyone have experience creating new users directly from your code ?

Answer:

It’s actually quite easy if you follow the development documentation (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html), more specifically the “signUp” function.

From the Docs:

And using this, it’s simple to create a user (example in Lambda, but can easily be modified as JS on its own):

Anything you set to required in your Cognito pool setup has to be in the UserAttributes section (usually the email is defaulted to required, check if yours is). The list of things you can assign values to is found in (Cognito pool) General Settings -> App Clients -> Show Details -> Set Read/Write -> (list of things), here you can add custom attributes (like if you want to specify what city your user is from, or if you want to add whatever else (String/Number)).

When assigning a value to a custom field, your “Name” in the UserAttributes will be “custom:whatever”, so if the custom field is “city” the Name is “custom:city”.

Hopefully I wasn’t stating too much of the obvious, but these are things it took me a while to figure out with the broken up SO info, and AWS docs, and I figured I’d plop it all together.

Leave a Reply