How to change User Status FORCE_CHANGE_PASSWORD?

前端 未结 12 1926
我在风中等你
我在风中等你 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:29

    I know It is the same answer, but thought it might help Go developer community. basically it is initiating auth request, get the session and respond to the challenge NEW_PASSWORD_REQUIRED

    func sessionWithDefaultRegion(region string) *session.Session {
        sess := Session.Copy()
        if v := aws.StringValue(sess.Config.Region); len(v) == 0 {
            sess.Config.Region = aws.String(region)
        }
    
        return sess
    }
    
    
    
    func (c *CognitoAppClient) ChangePassword(userName, currentPassword, newPassword string)   error {
    
        sess := sessionWithDefaultRegion(c.Region)
        svc := cognitoidentityprovider.New(sess)
    
        auth, err := svc.AdminInitiateAuth(&cognitoidentityprovider.AdminInitiateAuthInput{
            UserPoolId:aws.String(c.UserPoolID),
            ClientId:aws.String(c.ClientID),
            AuthFlow:aws.String("ADMIN_NO_SRP_AUTH"),
            AuthParameters: map[string]*string{
                "USERNAME": aws.String(userName),
                "PASSWORD": aws.String(currentPassword),
            },
    
        })
    
    
    
        if err != nil {
            return err
        }
    
        request := &cognitoidentityprovider.AdminRespondToAuthChallengeInput{
            ChallengeName: aws.String("NEW_PASSWORD_REQUIRED"),
            ClientId:aws.String(c.ClientID),
            UserPoolId: aws.String(c.UserPoolID),
            ChallengeResponses:map[string]*string{
                "USERNAME":aws.String(userName),
                "NEW_PASSWORD": aws.String(newPassword),
            },
            Session:auth.Session,
        }
    
    
        _, err = svc.AdminRespondToAuthChallenge(request)
    
        return err 
    }
    

    Here's a unit test:

    import (
        "fmt"
        "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
        . "github.com/smartystreets/goconvey/convey"
        "testing"
    )
    
    
    func TestCognitoAppClient_ChangePassword(t *testing.T) {
    
    
        Convey("Testing ChangePassword!", t, func() {
            err := client.ChangePassword("user_name_here", "current_pass", "new_pass")
    
    
    
            Convey("Testing ChangePassword Results!", func() {
                So(err, ShouldBeNil)
    
            })
    
        })
    }
    
    0 讨论(0)
  • 2020-12-07 08:35

    Basically this is the same answer but for .Net C# SDK:

    The following will make a full admin user creation with desired username and password. Having the following User model:

    public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    

    You can create a user and make it ready to use using:

       public void AddUser(User user)
        {
            var tempPassword = "ANY";
            var request = new AdminCreateUserRequest()
            {
                Username = user.Username,
                UserPoolId = "MyuserPoolId",
                TemporaryPassword = tempPassword
            };
            var result = _cognitoClient.AdminCreateUserAsync(request).Result;
            var authResponse = _cognitoClient.AdminInitiateAuthAsync(new AdminInitiateAuthRequest()
            {
                UserPoolId = "MyuserPoolId",
                ClientId = "MyClientId",
                AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
                AuthParameters = new Dictionary<string, string>()
                {
                    {"USERNAME",user.Username },
                    {"PASSWORD", tempPassword}
                }
            }).Result;
            _cognitoClient.RespondToAuthChallengeAsync(new RespondToAuthChallengeRequest()
            {
             ClientId = "MyClientId",
                ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
                ChallengeResponses = new Dictionary<string, string>()
                {
                    {"USERNAME",user.Username },
                    {"NEW_PASSWORD",user.Password }
                },
                Session = authResponse.Session
            });
        }
    
    0 讨论(0)
  • 2020-12-07 08:39

    Just add this code after your onSuccess: function (result) { ... }, within your login function. Your user will then have status CONFIRMED.

    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);
    }
    
    0 讨论(0)
  • 2020-12-07 08:39

    OK. I finally have code where an administrator can create a new user. The process goes like this:

    1. Admin creates the user
    2. User receives an email with their temporary password
    3. User logs in and is asked to change their password

    Step 1 is the hard part. Here's my code for creating a user in Node 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);
          }
        });
      }
    });
    

    Basically, you need to send a second command to force the email to be considered verified. The user still needs to go to their email to get the temporary password (which also verifies the email). But without that second call that sets the email to verified, you won't get the right call back to reset their password.

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

    not sure if you are still fighting with this but for creating a bunch of test users only, I used the awscli as such:

    1. Use the sign-up subcommand from cognito-idp to create the user
    aws cognito-idp sign-up \
       --region %aws_project_region% \
       --client-id %aws_user_pools_web_client_id% \
       --username %email_address% \
       --password %password% \
       --user-attributes Name=email,Value=%email_address%
    
    1. Confirm the user using admin-confirm-sign-up
    aws cognito-idp admin-confirm-sign-up \
    --user-pool-id %aws_user_pools_web_client_id% \
    --username %email_address%
    
    0 讨论(0)
  • 2020-12-07 08:48

    I know it's been a while but thought this might help other people who come across this post.

    You can use the AWS CLI to change the users password, however it's a multi step process:


    Step 1: Get a session token for the desired user:

    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%
    

    If this returns an error about Unable to verify secret hash for client, create another app client without a secret and use that client ID.

    Step 2: If step 1 is successful, it will respond with the challenge NEW_PASSWORD_REQUIRED, other challenge parameters and the users session key. Then, you can run the second command to issue the challenge response:

    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 ""%
    

    If you get an error about Invalid attributes given, XXX is missing pass the missing attributes using the format userAttributes.$FIELD_NAME=$VALUE

    The above command should return a valid Authentication Result and appropriate Tokens.


    Important: For this to work, the Cognito User Pool MUST have an App client configured with ADMIN_NO_SRP_AUTH functionality (Step 5 in this doc).

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