You can solve this problem using the amazon-cognito-identity-js SDK by authenticating with a temporary password after creating an account with cognitoidentityserviceprovider.adminCreateUser() and running cognitoUser.completeNewPasswordChallenge() inside cognitoUser.authenticateUser( ,{newPasswordRequired}) - everything inside the function that creates the user.
I am using the code below inside AWS lambda to create Cognito user accounts. I am sure that it can be optimized, be patient with me. This is my first post, and I'm still pretty new to JavaScript.
var AWS = require("aws-sdk"); var AWSCognito = require("amazon-cognito-identity-js"); var params = { UserPoolId: your_poolId, Username: your_username, DesiredDeliveryMediums: ["EMAIL"], ForceAliasCreation: false, MessageAction: "SUPPRESS", TemporaryPassword: your_temporaryPassword, UserAttributes: [ { Name: "given_name", Value: your_given_name }, { Name: "email", Value: your_email }, { Name: "phone_number", Value: your_phone_number }, { Name: "email_verified", Value: "true" } ] }; var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider(); let promise = new Promise((resolve, reject) => { cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) { if (err) { reject(err); } else { resolve(data); } }); }); promise .then(data => { // login as new user and completeNewPasswordChallenge var anotherPromise = new Promise((resolve, reject) => { var authenticationDetails = new AWSCognito.AuthenticationDetails({ Username: your_username, Password: your_temporaryPassword }); var poolData = { UserPoolId: your_poolId, ClientId: your_clientId }; var userPool = new AWSCognito.CognitoUserPool(poolData); var userData = { Username: your_username, Pool: userPool }; var cognitoUser = new AWSCognito.CognitoUser(userData); let finalPromise = new Promise((resolve, reject) => { cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function(authResult) { cognitoUser.getSession(function(err) { if (err) { } else { cognitoUser.getUserAttributes(function( err, attResult ) { if (err) { } else { resolve(authResult); } }); } }); }, onFailure: function(err) { reject(err); }, newPasswordRequired(userAttributes, []) { delete userAttributes.email_verified; cognitoUser.completeNewPasswordChallenge( your_newPoassword, userAttributes, this ); } }); }); finalPromise .then(finalResult => { // signout cognitoUser.signOut(); // further action, eg email to new user resolve(finalResult); }) .catch(err => { reject(err); }); }); return anotherPromise; }) .then(() => { resolve(finalResult); }) .catch(err => { reject({ statusCode: 406, error: err }); });
source share