gpt4 book ai didi

reactjs - 使用 Amplify 保留 AWS Cognito 用户

转载 作者:行者123 更新时间:2023-12-03 13:49:38 26 4
gpt4 key购买 nike

我一直在关注Serverless Stack tutorial并且可以通过调用 Auth.signIn(username, passsword)

获得肯定的响应

我们当前的工作流程是用户需要重置密码,因为帐户将被分发。

.changePassword 函数需要 3 个参数;用户、旧密码、新密码

我一生都无法弄清楚它在为用户寻找什么。当我设置从 .signIn() 返回的对象时,出现以下错误:

Local storage is missing an ID Token, Please authenticate

显然我不会使用这个流程进行生产,但我正在尝试找出 Auth 正在寻找的内容。

Auth.signIn(this.state.emailAddress, this.state.password)
.then(user => {
this.setState({ isLoading: false, user });
}).then(async () => {
Auth.changePassword(this.state.user, 'P@ssw0rd!', 'NewP@ssw0rd!');
}).catch(err => {
this.setState({ isLoading: false, errorMessage: err.message })
});

我确实在 .signIn 返回的对象的 Storage 属性中看到了一个 ID token 。澄清一下:我可能不应该把它放在链接中。我在实践中并没有真正做到上面的事情。当我保存登录的响应并将其传递给changePassword 时,出现本地存储错误。我想知道设置 Amplify 时是否存在配置问题,通常会将这些信息放入 localStorage。

最佳答案

Auth.changePassword接受 CognitoUser 作为第一个参数,should be returned来自Auth.signIn

这里的问题是你的 promise 链接,以及使用 this.setState() 并在实际设置之前将其读回:

Auth.signIn(this.state.emailAddress, this.state.password)
.then(user => {
// Triggers a setstate here:
this.setState({ isLoading: false, user });
}).then(async () => {
// this.state.user is not defined at this point
Auth.changePassword(this.state.user, 'P@ssw0rd!', 'NewP@ssw0rd!');
}).catch(err => {
this.setState({ isLoading: false, errorMessage: err.message })
});

来自React docs :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

解决此问题的最简单方法是在第一个 .then 回调中返回用户,将其传递给第二个:

Auth.signIn(this.state.emailAddress, this.state.password)
.then(user => {
// Triggers a setstate here:
this.setState({ isLoading: false, user });
return user;
}).then((user) => {
// this.state.user is not defined at this point
Auth.changePassword(user, 'P@ssw0rd!', 'NewP@ssw0rd!');
}).catch(err => {
this.setState({ isLoading: false, errorMessage: err.message })
});

就我个人而言,我认为完全使用 async/await 看起来会更好:

try {
const user = await Auth.signIn(this.state.emailAddress, this.state.password);

this.setState({ isLoading: false, user });

await Auth.changePassword(user, 'P@ssw0rd!', 'NewP@ssw0rd!');
} catch (err) {
this.setState({ isLoading: false, errorMessage: err.message })
}

关于reactjs - 使用 Amplify 保留 AWS Cognito 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com