我有基本的 react 应用程序,我正在尝试使用 aws-amplify 进行身份验证。
我在 cognito 中设置了一个用户池。我能够将用户发送到托管用户界面。用户能够登录,但是当我尝试获取当前 session 时,我收到一条消息,指出没有当前用户
。
这是我的代码。
import React, { Component } from 'react';
import './App.css';
import Amplify, { Auth } from 'aws-amplify';
import awsmobile from "./aws-exports";
const auth = {
AppWebDomain: "funnybusty.auth.us-east-2.amazoncognito.com",
TokenScopesArray: ["phone", "email", "profile", "openid", "aws.cognito.signin.user.admin"],
RedirectUriSignIn: "http://localhost:3000",
RedirectUriSignOut: "http://localhost:3000",
responseType: "token",
ClientId: "aaaaa",
UserPoolId: "aaaa",
};
Amplify.configure(awsmobile);
Auth.configure({ oauth: auth });
class App extends Component {
componentDidMount() {
Auth.currentSession()
.then(data => console.log(data))
.catch(err => console.log(err));
}
click = () => {
const config = Auth.configure().oauth
const url = 'https://' + config.AppWebDomain + '/login?redirect_uri=' + config.RedirectUriSignIn + '&response_type=' + config.responseType + '&client_id=' + config.ClientId;
window.location.assign(url);
}
render() {
return (
<div className="App">
<button onClick={this.click}>
Sign in with AWS
</button>
</div>
);
}
}
export default App;
我哪里出错了?
最佳答案
我从未使用过reactjs,但我注意到了一些事情:
- 您必须使用Hub 模块来监听
signIn
事件。否则,您将无法取回您的用户信息。 - 在您的 oauth 配置中,您必须使用 http://localhost:3000/ 定义您的
redirectSignIn
和redirectSignOut
(最后的/
很重要,我是通过艰难的方式才学会的..) 您可能必须将
ClientId
和UserPoolId
从 const auth 中移出,因为 oauth 配置的模式是:const oauth = { domain: 'your_cognito_domain', scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'], redirectSignIn: 'http://localhost:3000/', redirectSignOut: 'http://localhost:3000/', responseType: 'code' // or token };
有关更多信息,您可以查看文档中提供的完整示例:https://aws-amplify.github.io/docs/js/authentication#make-it-work-in-your-app
关于javascript - Auth.currentSession 表示没有当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539826/