Подтвердить что ты не робот

Как установить пароль пользователя cognito в качестве администратора?

Через API-интерфейс cognito admin, как установить пароль для пользователей? Когда пользователь создается, я могу установить временный пароль, мне нужно сделать это для существующего пользователя.

4b9b3361

Ответ 1

РЕДАКТИРОВАТЬ-2: новейшая версия API Cognito теперь поддерживает AdminSetUserPassword. Проверьте ответ @Pedro del Sol ниже.

Вы не можете установить пароль пользователя, единственное, что вы можете сделать, это использовать AdminResetUserPassword.

РЕДАКТИРОВАТЬ: Вы также можете позвонить ForgotPassword. Но, как следует из названия, он должен вызываться пользователем, а не администратором.

Ответ 2

В новейшей версии API Cognito добавлено действие AdminSetUserPassword, которое имеет синтаксис запроса, подобный следующему

{
   "Password": "string",
   "Permanent": boolean,
   "Username": "string",
   "UserPoolId": "string"
}

и позволит вам установить постоянный или временный пароль для данного пользователя.

Ответ 3

Как сказал @Stu, похоже, что adminResetUserPassword в настоящее время является единственным способом. Один из хакерских способов заключается в том, чтобы сначала изменить адрес электронной почты пользователя, сбросить пароль пользователя, получить код из вашего почтового ящика, изменить пароль и затем изменить адрес электронной почты.

Вот сценарий Node.js, чтобы в основном автоматизировать это:

const Promise = require('bluebird');
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(Promise);
AWS.config.update({region: process.env.AWS_DEFAULT_REGION ? process.env.AWS_DEFAULT_REGION : 'us-west-2'});
const cognitoIsp = new AWS.CognitoIdentityServiceProvider();
const readline = require('readline');

// process.argv[0]: (node)
// process.argv[1]: (this script)
// process.argv[2]: user-pool-id
// process.argv[3]: client-id
// process.argv[4]: username
// process.argv[5]: new-password
// process.argv[6]: your-email

if (process.argv.length < 7) {
    console.error('usage: node ${process.argv[1]} <user-pool-id> <client-id> <username> <new-password> <your-email>');
    process.exit(1);
}
const userPoolId = process.argv[2];
const clientId = process.argv[3];
const username = process.argv[4];
const newPassword = process.argv[5];
const adminEmail = process.argv[6];

let existingAttributes;

cognitoIsp.adminGetUser({
    UserPoolId: userPoolId,
    Username: username
}).promise().then(function (user) {
    existingAttributes = user.UserAttributes;
    console.log('=== Attributes that will be temporarily overwritten by this script ===');
    console.log('In case of unrecoverable error, they are displayed here so you can manually restore them through the AWS console.');
    const displayAttributeNames = ['email', 'email_verified', 'phone', 'phone_verified'];
    const attributesToDisplay = existingAttributes.filter((attribute) => displayAttributeNames.includes(attribute.Name));
    console.log(JSON.stringify(attributesToDisplay, null, 4));
}).then(function () {
    return cognitoIsp.adminUpdateUserAttributes({
        UserAttributes: [
            {Name: 'email', Value: adminEmail},
            {Name: 'email_verified', Value: 'true'}
        ],
        UserPoolId: userPoolId,
        Username: username
    }).promise();
}).then(function () {
    // temporarily remove phone because cognito will use it over email if present
    const unwantedAttributeNames = ['phone', 'phone_verified'];
    const attributesToDelete = existingAttributes.filter((attribute) => unwantedAttributeNames.includes(attribute.Name));
    if (attributesToDelete.length > 0) {
        return cognitoIsp.adminDeleteUserAttributes({
            UserAttributeNames: attributesToDelete,
            UserPoolId: userPoolId,
            Username: username
        }).promise();
    }
}).then(function () {
    return cognitoIsp.adminResetUserPassword({
        UserPoolId: userPoolId,
        Username: username
    }).promise();
}).then(function () {
    return new Promise(function (resolve, reject) {
        let resetCode;
        const rl = readline.createInterface(process.stdin, process.stdout);
        rl.setPrompt('Enter the password reset code sent to ${adminEmail}: ');
        rl.prompt();
        rl.on('line', function (line) {
            resetCode = line;
            rl.close();
        }).on('close', function () {
            resolve(resetCode);
        }).on('error', function (err) {
            reject(err);
        });
    });
}).then(function (code) {
    return cognitoIsp.confirmForgotPassword({
        ClientId: clientId,
        ConfirmationCode: code,
        Password: newPassword,
        Username: username
    }).promise();
}).then(function () {
    return restoreAttributes();
}).then(function () {
    console.log('All done, password for ${username} is now ${newPassword}');
}).catch(function (err) {
    console.log('ERROR:', err);
    console.log('Attempting to restore original attributes...');
    return restoreAttributes().then(function () {
        console.log('Original attributes were successfully restored');
    }).catch(function (err) {
        console.log('ERROR:', err);
        console.log('Unable to restore original attributes, please see output above and restore them manually through the AWS console');
    }).finally(function () {
        process.exit(1);
    });
});

function restoreAttributes() {
    const wantedAttributeNames = ['email', 'email_verified', 'phone', 'phone_verified'];
    const attributesToRestore = existingAttributes.filter((attribute) => wantedAttributeNames.includes(attribute.Name));
    return cognitoIsp.adminUpdateUserAttributes({
        UserAttributes: attributesToRestore,
        UserPoolId: userPoolId,
        Username: username
    }).promise();
}

Редактирование: я должен добавить, что, конечно, как админы, с большой властью несет большую ответственность, поэтому убедитесь, что ваш случай использования достаточно оправдан, чтобы изменить адрес электронной почты пользователя самостоятельно, даже временно.