Aditya
Aditya

Reputation: 51

Aws cognito create user by admin nodejs

I am using javascript sdk amazon-cognito-identity-js and i am trying to create a user in cognito in nodejs but error is coming below is my code:-

var AWS = require("aws-sdk")
var params = {
    UserPoolId: "id",
    Username: req.body.username,
    DesiredDeliveryMediums: ["EMAIL"],
    ForceAliasCreation: false,
    TemporaryPassword: req.body.password,
    UserAttributes: [
      { Name: "name", Value: req.body.name },
      { Name: "email", Value: req.body.user_email}
    ],
 };
let client = new AWS.CognitoIdentityServiceProvider();
client.adminCreateUser(params, function(err, data) {
    if (err) {
        console.log("EE",err);
      //  reject(err);
    } else {
        console.log("DDD",data);
        //resolve(data);
    }
})

But i am getting this error using the code:-

EE { UnknownError: Not Found at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:48:27) }

Please Help me Out to figure out this issue.

Upvotes: 4

Views: 13871

Answers (3)

CharlesA
CharlesA

Reputation: 4350

And for AWS SDK v3 and ES6:

Install the Library

npm install @aws-sdk/client-cognito-identity-provider --save

Import the Module

import { CognitoIdentityProviderClient, AdminCreateUserCommand } from "@aws-sdk/client-cognito-identity-provider";

Create the Client

const cognitoClient = new CognitoIdentityProviderClient({ region: 'eu-west-1' });

Create the User

const command = new AdminCreateUserCommand({
      UserPoolId: USER_POOL_ID,
      Username: EMAIL_ADDRESS,
      DesiredDeliveryMediums: ['EMAIL'],
      TemporaryPassword: TEMPORARY_PASSWORD
    });

let response = await cognitoClient.send(command);

Note that you'll need to have cognito-idp:AdminCreateUser permission for this to work.

Upvotes: 2

Amarnathrao Sulake
Amarnathrao Sulake

Reputation: 481

ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: admin-create-user.js demonstrates how an administrator can use Amazon Cognito to create a user.

Inputs:

  • USERPOOLID
  • EMAIL

AWS configuration

const AWS = require("aws-sdk");

AWS.config.update({
  accessKeyId : "Your accessKeyId ",
  secretAccessKey: "secretAccessKey",
});

CREATE COGNITO_CLIENT

const COGNITO_CLIENT = new AWS.CognitoIdentityServiceProvider({
  apiVersion: "2022-10-03",
  region: "us-east-1",
});

CREATE USER

const createUser = async (user) => {
  try {
    const { emailId, password } = user;
    const cognitoParams = {
      UserPoolId: userPoolId,
      Username: emailId,
      UserAttributes: [
        {
          Name: "email",
          Value: emailId,
        },
        {
          Name: "email_verified",
          Value: "true",
        },
      ],
      TemporaryPassword: password || "Password@123456789",
    };

    console.log(cognitoParams.TemporaryPassword);

    let response = await COGNITO_CLIENT.adminCreateUser(
      cognitoParams
    ).promise();
    console.log(JSON.stringify(response));
    return "user created";
  } catch (err) {
    throw Error(err);
  }
};

Upvotes: 0

Ashish Kadam
Ashish Kadam

Reputation: 1487

Here is the solution.

Pre-requirement If you want to use the credential in aws-sdk (Manual Process) 1. Create IAM User and Assign a Cognito role to your user. 2. Generate Access Key and Secret Key for that user. 3. Use that Access Key and Secret Key in aws-sdk.

Like This,

let AWS = require("aws-sdk");
AWS.config.update({
    accessKeyId: "YOURKEY",
    secretAccessKey: "YOURSECRET",
    region: "YOURREGION"
});

Create object of CognitoIdentityServiceProvider class

const COGNITO_CLIENT = new AWS.CognitoIdentityServiceProvider({
  apiVersion: "2016-04-19",
  region: "us-east-1"
});


var poolData = {
    UserPoolId: "XXXXXXXXX",
    Username: "[email protected]",
    DesiredDeliveryMediums: ["EMAIL"],
    TemporaryPassword: "Abc@321",
    UserAttributes: [
      {
        Name: "email",
        Value: "[email protected]"
      },
      {
        Name: "email_verified",
        Value: "true"
      }
    ]
  };
  COGNITO_CLIENT.adminCreateUser(poolData, (error, data) => {
    console.log(error);
    console.log(data);
    callback(null, {
      statusCode: 200,
      body: JSON.stringify(data)
    });
  });

Or else you can directly assign IAM Role to your EC2 Instance in that case you do not need to set credentials in AWS.config Section.

Upvotes: 6

Related Questions