Cognito AdminCreateUser设置密码并确认

时间:2017-09-23 13:20:35

标签: aws-sdk

使用Cognito的AdminCreateUser时如何在用户创建时指定永久密码?此外,如何将此用户设置为“已确认”?

1 个答案:

答案 0 :(得分:0)

从大量研究文档开始,至少需要两个步骤-使用临时密码创建用户,并通过设置永久密码来“完成”其注册。发布NodeJS解决方案。

  1. 首先,您使用SDK使用临时(未真正使用)的密码创建用户:
import { CognitoIdentityServiceProvider } from 'aws-sdk';

const adminCreateUser = async (
  username: string,
  password: string
): Promise<void> => {
  return new Promise<void>((resolve, reject) => {
    new CognitoIdentityServiceProvider({
      region: '<Pool region>',
      accessKeyId: '<AWS user access key id>',
      secretAccessKey: '<AWS user access secret>',
    }).adminCreateUser(
      {
        Username: username,
        TemporaryPassword: password,
        UserPoolId: '<Cognito User Pool ID>',
      },
      (err, result) => {
        if (err) {
          return reject(err);
        }

        resolve();
      }
    );
  });
};
  1. 根据docs,我们需要调用authenticateUser来触发newPassowrdRequired回调,在这种情况下,我们使用永久密码调用completeNewPasswordChallenge
import {
  AuthenticationDetails,
  CognitoUser,
  CognitoUserPool,
} from 'amazon-cognito-identity-js';

export const cognitoPool: CognitoUserPool = new CognitoUserPool({
  UserPoolId: '<Cognito Pool ID>',
  ClientId: '<Cognito App Client ID>',
});

export const adminConfirmUser = async (
  username: string,
  password: string
): Promise<void> => {
  return new Promise<void>((resolve, reject) => {
    const cognitoUser = new CognitoUser({
      Username: username,
      Pool: cognitoPool,
    });

    cognitoUser.authenticateUser(
      new AuthenticationDetails({
        Username: username,
        Password: password,
      }),
      {
        onSuccess: (session, userConfirmationNecessary) => {
          // User is already confirmed
          resolve();
        },
        onFailure: err => {
          // An error
          reject(err);
        },
        newPasswordRequired: (userAttributes, requiredAttributes) => {
          cognitoUser.completeNewPasswordChallenge(password, null, {
            onSuccess: session => {
              // User confirmed
              resolve();
            },
            onFailure: err => {
              // Error confirming user
              reject(err);
            },
          });
        },
      }
    );
  });
};

请注意,取决于您设置Cognito池的方式,在确认用户注册时可能需要传递必需的属性。