使用Cognito的AdminCreateUser
时如何在用户创建时指定永久密码?此外,如何将此用户设置为“已确认”?
答案 0 :(得分:0)
从大量研究文档开始,至少需要两个步骤-使用临时密码创建用户,并通过设置永久密码来“完成”其注册。发布NodeJS解决方案。
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();
}
);
});
};
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池的方式,在确认用户注册时可能需要传递必需的属性。