简体   繁体   English

如何允许我的用户在 Cognito 用户池上重置密码?

[英]How to allow my user to reset their password on Cognito User Pools?

So in my app I obviously want to provide the means for users to reset their passwords.所以在我的应用程序中,我显然想为用户提供重置密码的方法。 The issue I'm having though is that the new documentation for User Pools is pretty ambiguous on this topic.我遇到的问题是用户池的新文档在这个主题上非常模糊。 Here is what they tell you to do for a Forgot Password flow, and the link you may find it at:以下是他们告诉您为忘记密码流程执行的操作,以及您可以在以下位置找到的链接:

cognitoUser.forgotPassword({
        onSuccess: function (result) {
            console.log('call result: ' + result);
        },
        onFailure: function(err) {
            alert(err);
        },
        inputVerificationCode() {
            var verificationCode = prompt('Please input verification code ' ,'');
            var newPassword = prompt('Enter new password ' ,'');
            cognitoUser.confirmPassword(verificationCode, newPassword, this);
        }
    });

http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html

However when I drop this code into my project where a cognitoUser is defined and signed in, nothing seems to happen.但是,当我将此代码放入定义并登录了 cognitoUser 的项目中时,似乎什么也没有发生。 I understand I need to somehow integrate this code with sending a verification code to the user, and asking them for a new password, but can't find anything on how to do this.我知道我需要以某种方式将此代码与向用户发送验证码并要求他们输入新密码相集成,但找不到有关如何执行此操作的任何信息。 Thoughts?想法?

Thanks谢谢

AWS' docs are terrible on this topic (Cognito). AWS 的文档在这个主题上很糟糕(Cognito)。 You basically need to setup cognitoUser , then call forgotPassword您基本上需要设置cognitoUser ,然后调用forgotPassword

export function resetPassword(username) {
    // const poolData = { UserPoolId: xxxx, ClientId: xxxx };
    // userPool is const userPool = new AWSCognito.CognitoUserPool(poolData);

    // setup cognitoUser first
    cognitoUser = new AWSCognito.CognitoUser({
        Username: username,
        Pool: userPool
    });

    // call forgotPassword on cognitoUser
    cognitoUser.forgotPassword({
        onSuccess: function(result) {
            console.log('call result: ' + result);
        },
        onFailure: function(err) {
            alert(err);
        },
        inputVerificationCode() { // this is optional, and likely won't be implemented as in AWS's example (i.e, prompt to get info)
            var verificationCode = prompt('Please input verification code ', '');
            var newPassword = prompt('Enter new password ', '');
            cognitoUser.confirmPassword(verificationCode, newPassword, this);
        }
    });
}

// confirmPassword can be separately built out as follows...  
export function confirmPassword(username, verificationCode, newPassword) {
    cognitoUser = new AWSCognito.CognitoUser({
        Username: username,
        Pool: userPool
    });

    return new Promise((resolve, reject) => {
        cognitoUser.confirmPassword(verificationCode, newPassword, {
            onFailure(err) {
                reject(err);
            },
            onSuccess() {
                resolve();
            },
        });
    });
}

Resetting the password with forgot password flow has two steps:使用忘记密码流程重置密码有两个步骤:

  1. Start the process by requesting for a verification code from the service.通过从服务请求验证码开始该过程。 A code will be delivered to the user's phone/email.代码将发送到用户的电话/电子邮件。
  2. Set the new password using the delivered verification code.使用提供的验证码设置新密码。

Use these two functions to perform the above steps and reset the password:使用这两个函数执行上述步骤并重置密码:

  1. cognitoUser.forgotPassword() : This will start the forgot password process flow. cognitoUser.forgotPassword() :这将启动忘记密码流程。 The service generates a verification code and sends it to the user.该服务生成验证码并将其发送给用户。 The "data", returned through callback.inputVerificationCode(data), indicates where the verification code was sent.通过 callback.inputVerificationCode(data) 返回的“数据”表示验证码发送到哪里。

  2. cognitoUser.confirmPassword() : Use the delivered verification code with this function to set a new password. cognitoUser.confirmPassword() :使用此函数提供的验证码设置新密码。

I had this same issue.我有同样的问题。 Was able to work through it by using confirmPassword() in the following way.可以通过以下方式使用 confirmPassword() 来解决它。

//validation of input from form
req.checkBody('email', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('confirmationcode', 'Confirmation Code is required').notEmpty();


var confirmationCode = req.body.confirmationcode;
var password = req.body.password;
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);


var userData = {
    Username: req.body.email,
    Pool: userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

cognitoUser.confirmPassword(confirmationCode, password, {
    onFailure(err) {
        console.log(err);
    },
    onSuccess() {
        console.log("Success");
    },
});

If as me, you find how to handle this case with amplify如果像我一样,您发现如何使用放大来处理这种情况

import { Auth } from 'aws-amplify';

// Send confirmation code to user's email
Auth.forgotPassword(username)
    .then(data => console.log(data))
    .catch(err => console.log(err));

// Collect confirmation code and new password, then
Auth.forgotPasswordSubmit(username, code, new_password)
    .then(data => console.log(data))
    .catch(err => console.log(err));

See https://docs.amplify.aws/lib/auth/manageusers/q/platform/js#forgot-password请参阅https://docs.amplify.aws/lib/auth/manageusers/q/platform/js#forgot-password

So Even I faced a same issue, Even in AWS cognito documentation it was not clear, basically the process involves two steps.所以即使我遇到了同样的问题,即使在 AWS cognito 文档中也不清楚,基本上这个过程包括两个步骤。

  1. call cognitoUser.forgotPassword() this will start forgot password process flow, and the user will receive a verification code.调用 cognitoUser.forgotPassword() 这将启动忘记密码流程,用户将收到验证码。
  2. then call cognitoUser.confirmPassword() which will reset the password verifying the code send to the email of user.然后调用 cognitoUser.confirmPassword() 这将重置密码以验证发送到用户电子邮件的代码。

Below I have given a cognitoUserClass(Typescript) which has static methods forgotPassword() and confirmPassword() methods which implements those two steps.下面我给出了一个 cognitoUserClass(Typescript),它具有实现这两个步骤的静态方法 forgotPassword() 和 confirmPassword() 方法。

import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js'

class cognitoUserClass {
    static cognitouser: AmazonCognitoIdentity.CognitoUser
    static userPool = new AmazonCognitoIdentity.CognitoUserPool({
        UserPoolId: 'your pool id',
        ClientId: 'your client id',
    })
    static forgotPassword(userName: string): void {
        const userData = {
            Username: userName,
            Pool: cognitoUserClass.userPool,
        }
        cognitoUserClass.cognitouser = new AmazonCognitoIdentity.CognitoUser(
            userData
        )

        cognitoUserClass.cognitouser.forgotPassword({
            onSuccess: (data) => {
                console.log(data)
            },
            onFailure: (err) => {
                console.log('ERR:', err)
            },
        })
    }
    static confirmPassword(
        verificationCode: string,
        newPassword: string
    ): void {
        cognitoUserClass.cognitouser.confirmPassword(
            verificationCode,
            newPassword,
            {
                onFailure(err) {
                    console.log(err)
                },
                onSuccess(data) {
                    console.log(data)
                },
            }
        )
    }
}

export { cognitoUserClass }

After you've got the verification code, using aws-amplify it's as easy as follows拿到验证码后,使用aws-amplify就很简单如下

import { Auth } from "aws-amplify";

Auth.forgotPasswordSubmit(email, verificationCode, newPassword)
    .then(() => {
        //redirect to sign-in page
    })
    .catch(error => {
        //error logic
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何允许我的用户使用 mobilen-number 或 email 地址在 Cognito 用户池上重置密码? - How to allow my users to use either mobilen-number or email address to reset their password on Cognito User Pools? 如何重置 AWS Cognito 用户的密码? - How to reset password of AWS Cognito user? 如何在不验证电子邮件或电话的情况下确认 Cognito 用户池中的用户? - How to confirm user in Cognito User Pools without verifying email or phone? 如何在 apollo-client 中使用 AMAZON_COGNITO_USER_POOLS - How to use AMAZON_COGNITO_USER_POOLS with apollo-client AWS cognito用户池,自定义消息lambda - AWS cognito user pools, custom message lambda AWS Cognito Admin创建的用户临时密码验证并重置 - AWS Cognito Admin created user temp password verify & reset AWS Cognito:如何需要密码才能更改用户属性或删除用户? - AWS Cognito: How Require Password for changing User Attributes or Delete User? AWS Cognito:更改 aws_user_pools_web_client_id - AWS Cognito: changing the aws_user_pools_web_client_id 限制AWS Cognito用户池javascript api的请求来源 - Restricting request origin for AWS Cognito User Pools javascript api 使用 Cognito 用户池向 AWS AppSync 验证 Apollo 客户端 - Authenticate Apollo Client to AWS AppSync with Cognito User Pools
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM