How to change User Status FORCE_CHANGE_PASSWORD?

前端 未结 12 1879
我在风中等你
我在风中等你 2020-12-07 08:15

Using AWS Cognito, I want to create dummy users for testing purposes.

I then use the AWS Console to create such user, but the user has its status s

相关标签:
12条回答
  • 2020-12-07 08:24

    You can change that user status FORCE_CHANGE_PASSWORD by calling respondToAuthChallenge() on the user like this:

    var params = {
      ChallengeName: 'NEW_PASSWORD_REQUIRED', 
      ClientId: 'your_own3j6...0obh',
      ChallengeResponses: {
        USERNAME: 'user3',
        NEW_PASSWORD: 'changed12345'
      },
      Session: 'xxxxxxxxxxZDMcRu-5u...sCvrmZb6tHY'
    };
    
    cognitoidentityserviceprovider.respondToAuthChallenge(params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });
    

    After this, you'll see in the console that user3 status is CONFIRMED.

    0 讨论(0)
  • 2020-12-07 08:28

    This has finally been added to AWSCLI: https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-set-user-password.html

    You can change a user's password and update status using:

    aws cognito-idp admin-set-user-password --user-pool-id <your user pool id> --username user1 --password password --permanent

    Before using this, you may need to update your AWS CLI using:

    pip3 install awscli --upgrade

    0 讨论(0)
  • UPDATE:

    I am now using this, translated to amplify, inside a NodeJS Lambda:

    // enable node-fetch polyfill for Node.js
    global.fetch = require("node-fetch").default;
    global.navigator = {};
    
    const AWS = require("aws-sdk");
    const cisp = new AWS.CognitoIdentityServiceProvider();
    
    const Amplify = require("@aws-amplify/core").default;
    const Auth = require("@aws-amplify/auth").default;
    
    ...
    
    
    /*
      this_user: {
        given_name: string,
        password: string,
        email: string,
        cell: string
      }
    */
    const create_cognito = (this_user) => {
      let this_defaults = {
        password_temp: Math.random().toString(36).slice(-8),
        password: this_user.password,
        region: global._env === "prod" ? production_region : development_region,
        UserPoolId:
          global._env === "prod"
            ? production_user_pool
            : development_user_pool,
        ClientId:
          global._env === "prod"
            ? production_client_id
            : development_client_id,
        given_name: this_user.given_name,
        email: this_user.email,
        cell: this_user.cell,
      };
    
      // configure Amplify
      Amplify.configure({
        Auth: {
          region: this_defaults.region,
          userPoolId: this_defaults.UserPoolId,
          userPoolWebClientId: this_defaults.ClientId,
        },
      });
      if (!Auth.configure())
        return Promise.reject("could not configure amplify");
    
      return new Promise((resolve, reject) => {
        let _result = {};
    
        let this_account = undefined;
        let this_account_details = undefined;
    
        // create cognito account
        cisp
          .adminCreateUser({
            UserPoolId: this_defaults.UserPoolId,
            Username: this_defaults.given_name,
            DesiredDeliveryMediums: ["EMAIL"],
            ForceAliasCreation: false,
            MessageAction: "SUPPRESS",
            TemporaryPassword: this_defaults.password_temp,
            UserAttributes: [
              { Name: "given_name", Value: this_defaults.given_name },
              { Name: "email", Value: this_defaults.email },
              { Name: "phone_number", Value: this_defaults.cell },
              { Name: "email_verified", Value: "true" },
            ],
          })
          .promise()
          .then((user) => {
            console.warn(".. create_cognito: create..");
            _result.username = user.User.Username;
            _result.temporaryPassword = this_defaults.password_temp;
            _result.password = this_defaults.password;
    
            // sign into cognito account
            return Auth.signIn(_result.username, _result.temporaryPassword);
          })
          .then((user) => {
            console.warn(".. create_cognito: signin..");
    
            // complete challenge
            return Auth.completeNewPassword(user, _result.password, {
              email: this_defaults.email,
              phone_number: this_defaults.cell,
            });
          })
          .then((user) => {
            console.warn(".. create_cognito: confirmed..");
            this_account = user;
            // get details
            return Auth.currentAuthenticatedUser();
          })
          .then((this_details) => {
            if (!(this_details && this_details.attributes))
              throw "account creation failes";
    
            this_account_details = Object.assign({}, this_details.attributes);
    
            // signout
            return this_account.signOut();
          })
          .then(() => {
            console.warn(".. create_cognito: complete");
            resolve(this_account_details);
          })
          .catch((err) => {
            console.error(".. create_cognito: error");
            console.error(err);
            reject(err);
          });
      });
    };
    
    

    I am setting a temp password and then later resetting it to the user's requested password.

    OLD POST:

    You can solve this using the amazon-cognito-identity-js SDK by authenticating with the temporary password after the account creation with cognitoidentityserviceprovider.adminCreateUser(), and running cognitoUser.completeNewPasswordChallenge() within cognitoUser.authenticateUser( ,{newPasswordRequired}) - all inside the function that creates your user.

    I am using the below code inside AWS lambda to create enabled Cognito user accounts. I am sure it can be optimized, be patient with me. This is my first post, and I am 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, e.g. email to new user
                        resolve(finalResult);
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
            return anotherPromise;
        })
        .then(() => {
            resolve(finalResult);
        })
        .catch(err => {
            reject({ statusCode: 406, error: err });
        });
    
    0 讨论(0)
  • 2020-12-07 08:29

    Sorry you are having difficulties. We do not have a one step process where you can just create users and authenticate them directly. We might change this in the future such as to allow administrators to set passwords that are directly usable by users. For now, when you create users either using AdminCreateUser or by signing up users with the app, extra steps are required, either forcing users to change the password upon login or having users verify the email or phone number to change the status of the user to CONFIRMED.

    0 讨论(0)
  • 2020-12-07 08:29

    If you are trying to change status as a admin from the console. Then follow the below steps after creating the user.

    1. In Cognito goto -> "manage user pool" ->
    2. Goto "App client settings" under App integration section.
    3. Check on the below items i) Cognito User Pool ii) Authorization code grant iii) Implicit grant iv) phone v) email vi) openid vii) aws.cognito.signin.user.admin viii) profile
    4. Enter the callback url of your application. If you are not sure enter for example: https://google.com and later you can change it to your actual callback url
    5. click on save changes.
    6. Once changes are saved click on the link "Launch Hosted UI"
    7. Enter the credentials of the new created user
    8. Reset the password with new credentials and share the same to the user

    step 2

    step 3 4 5 6

    step 7

    step 8

    0 讨论(0)
  • 2020-12-07 08:29

    For Java SDK, assuming your Cognito client is setup and you have your user in the FORCE_CHANGE_PASSWORD state you can do the following to get your user CONFIRMED... and then auth'd as 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);
    

    Hope it helps with those integration tests (Sorry about the formatting)

    0 讨论(0)
提交回复
热议问题