¿Cómo cambiar el Estado del Usuario FORZAR EL CAMBIO DE CONTRASEÑA?


Con AWS Cognito, quiero crear usuarios ficticios con fines de prueba.

Luego uso la consola AWS para crear dicho usuario, pero el usuario tiene su estado establecido en FORCE_CHANGE_PASSWORD. Con ese valor, este usuario no se puede autenticar.

¿Hay alguna forma de cambiar este estado?

ACTUALIZAR Mismo comportamiento al crear usuario desde CLI

Author: Ryan Shillington, 2016-10-27

7 answers

Lamento que tenga dificultades. No tenemos un proceso de un solo paso donde solo puede crear usuarios y autenticarlos directamente. Podríamos cambiar esto en el futuro, por ejemplo, para permitir a los administradores establecer contraseñas que sean directamente utilizables por los usuarios. Por ahora, cuando crea usuarios utilizando AdminCreateUser o registrando usuarios con la aplicación, se requieren pasos adicionales, ya sea obligando a los usuarios a cambiar la contraseña al iniciar sesión o haciendo que los usuarios verifiquen el correo electrónico o el número de teléfono para cambiar el estado del usuario a CONFIRMADO.

 11
Author: Ionut Trestian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-02 20:49:07

Sé que ha pasado un tiempo, pero pensé que esto podría ayudar a otras personas que se encuentran con este post.

Puede usar la CLI de AWS para cambiar la contraseña de los usuarios, sin embargo, es un proceso de varios pasos:
Paso 1, es obtener un token de sesión para el usuario deseado:
aws cognito-idp admin-initiate-auth --user-pool-id %USER POOL ID% --client-id %APP CLIENT ID% --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=%USERS USERNAME%,PASSWORD=%USERS CURRENT PASSWORD%

Esto responderá con el desafío "NEW_PASSWORD_REQUIRED", otros parámetros de desafío y la clave de sesión del usuario. Luego, puede ejecutar el segundo comando para emitir la respuesta al desafío:
aws cognito-idp admin-respond-to-auth-challenge --user-pool-id %USER POOL ID% --client-id %CLIENT ID% --challenge-name NEW_PASSWORD_REQUIRED --challenge-responses NEW_PASSWORD=%DESIRED PASSWORD%,USERNAME=%USERS USERNAME% --session %SESSION KEY FROM PREVIOUS COMMAND with ""%

Esto debe devolver un resultado de autenticación válido y los Tokens apropiados.

Para que esto funcione, el Grupo de usuarios de Cognito DEBE tener un cliente de aplicación configurado con la funcionalidad ADMIN_NO_SRP_AUTH. (nota paso 5 http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)

 65
Author: Neutral Penguin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-23 19:26:41

Puede cambiar ese estado de usuario FORCE_CHANGE_PASSWORD llamando a RespondToAuthChallenge () en el usuario de la siguiente manera:

var params = {
  ChallengeName: 'NEW_PASSWORD_REQUIRED', 
  ClientId: 'your_own3j63rs8j16bxxxsto25db00obh',
  ChallengeResponses: {
    USERNAME: 'user3',
    NEW_PASSWORD: 'changed12345'
  },
  Session: 'xxxxxxxxxxZDMcRu-5u019i_gAcX5lw1biFnKLtfPrO2eZ-nenOLrr5xaHv-ul_-nGsOulyNG12H85GJ2UGiCGtfe-BdwTmQ-BMUnd2Twr9El45xgpGKWDrYcp11J4J9kZN71ZczynizRJ7oa5a_j2AiBYukzhd_YzPWGscrFu98qqn_JoiLsJ7w9v_C_Zpw6-ixCs09suYQKZ3YlWNFmMpC2nSiKrXUA8ybQkdj6vIO68d-vtYq0mVHt410v2TBtK4czOAh5MieO55kgvGHCxvEusQOTeFYh4Mjh1bwcHWRvSV6mVIrVSm4FnRs0u26vUDq79CgkuycRl2iOoqxc1abcaANKmEB45r2oPnmPZIhVqNO5eHe6fpac7s3pHwLKvNOv7EaQkjyY9Vb5gINmSjXBjBl3O3aqQ7KXyueuHHSLrfchP64SwuNQZSfL1Vis0ap5JtSat3udslzUBiU8FEhmJNwPX08QyIm4DqviTLp6lDqH5pH6BuvO9OUHPrEcDzufOx1a76pld-9f-NGfactCUZC0elQcAiGSqbwfiRYHn7TDHuX1WKf9L9E6GvhJhB154SxxhXsLm3Yv9DhWhOlVbhdbzR2Bq4dqJRDOPY2wengFX6v36TLlYZTHbGEc_PbSlx8Ru80avxehAmUNtNqDYjGbXq0vBWaEiJmkr1isF7XsCvrmZb6tHY'
};

cognitoidentityserviceprovider.respondToAuthChallenge(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Después de esto, verá en la consola que se CONFIRMA el estado de user3

 12
Author: Ariel Araza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-13 02:22:01

Simplemente agregue este código después de su onSuccess: function (result) { ... }, dentro de su función de inicio de sesión. Su usuario tendrá entonces status CONFIRMADO.

newPasswordRequired: function(userAttributes, requiredAttributes) {
    // User was signed up by an admin and must provide new
    // password and required attributes, if any, to complete
    // authentication.

    // the api doesn't accept this field back
    delete userAttributes.email_verified;

    // unsure about this field, but I don't send this back
    delete userAttributes.phone_number_verified;

    // Get these details and call
    cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
}
 11
Author: Baked Inhalf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 09:18:15

Puede resolver esto usando el SDK de amazon-cognito-identity-js autenticándose con la contraseña temporal después de la creación de la cuenta con cognitoidentityserviceprovider.adminCreateUser() y ejecutando cognitoUser.completeNewPasswordChallenge() dentro de cognitoUser.authenticateUser( ,{newPasswordRequired}) - todo dentro de la función que crea el usuario.

Estoy utilizando el siguiente código dentro de AWS lambda para crear cuentas de usuario de Cognito habilitadas. Estoy seguro de que se puede optimizar, sé paciente conmigo. Este es mi primer post, y todavía soy bastante nuevo en 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, e.g. email to new user
                    resolve(finalResult);
                })
                .catch(err => {
                    reject(err);
                });
        });
        return anotherPromise;
    })
    .then(() => {
        resolve(finalResult);
    })
    .catch(err => {
        reject({ statusCode: 406, error: err });
    });
 2
Author: qqan.ny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-19 18:42:45

Para el SDK de Java, suponiendo que su cliente de Cognito esté configurado y tenga a su usuario en el estado FORCE_CHANGE_PASSWORD, puede hacer lo siguiente para confirmar a su usuario... y, a continuación, auth había como normal.

AdminCreateUserResult createUserResult = COGNITO_CLIENT.adminCreateUser(createUserRequest());

AdminInitiateAuthResult authResult = COGNITO_CLIENT.adminInitiateAuth(authUserRequest());


Map<String,String> challengeResponses = new HashMap<>();
challengeResponses.put("USERNAME", USERNAME);
challengeResponses.put("NEW_PASSWORD", PASSWORD);
RespondToAuthChallengeRequest respondToAuthChallengeRequest = new RespondToAuthChallengeRequest()
      .withChallengeName("NEW_PASSWORD_REQUIRED")
      .withClientId(CLIENT_ID)
      .withChallengeResponses(challengeResponses)
      .withSession(authResult.getSession());

COGNITO_CLIENT.respondToAuthChallenge(respondToAuthChallengeRequest);

Espero que ayude con esas pruebas de integración (Lo siento por el formato)

 1
Author: HKalsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-30 21:28:18

OK. Finalmente tengo código donde un administrador puede crear un nuevo usuario. El proceso es así:

  1. El administrador crea el usuario
  2. El usuario recibe un correo electrónico con su contraseña temporal
  3. El usuario inicia sesión y se le pide que cambie su contraseña

El paso 1 es la parte difícil. Este es mi código para crear un usuario en el nodo JS:

let params = {
  UserPoolId: "@cognito_pool_id@",
  Username: username,
  DesiredDeliveryMediums: ["EMAIL"],
  ForceAliasCreation: false,
  UserAttributes: [
    { Name: "given_name", Value: firstName },
    { Name: "family_name", Value: lastName},
    { Name: "name", Value: firstName + " " + lastName},
    { Name: "email", Value: email},
    { Name: "custom:title", Value: title},
    { Name: "custom:company", Value: company + ""}
  ],
};
let cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
cognitoIdentityServiceProvider.adminCreateUser(params, function(error, data) {
  if (error) {
    console.log("Error adding user to cognito: " + error, error.stack);
    reject(error);
  } else {
    // Uncomment for interesting but verbose logging...
    //console.log("Received back from cognito: " + CommonUtils.stringify(data));
    cognitoIdentityServiceProvider.adminUpdateUserAttributes({
      UserAttributes: [{
        Name: "email_verified",
        Value: "true"
      }],
      UserPoolId: "@cognito_pool_id@",
      Username: username
    }, function(err) {
      if (err) {
        console.log(err, err.stack);
      } else {
        console.log("Success!");
        resolve(data);
      }
    });
  }
});

Básicamente, debe enviar un segundo comando para forzar que el correo electrónico se considere verificado. El usuario todavía necesita para ir a su correo electrónico para obtener la contraseña temporal (que también verifica el correo electrónico). Pero sin esa segunda llamada que establece el correo electrónico en verificado, no recibirá la llamada correcta para restablecer su contraseña.

 1
Author: Ryan Shillington,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-29 19:49:54