javascript - Auth.currentSession 表示没有当前用户

标签 javascript reactjs amazon-cognito aws-amplify

我有基本的 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,但我注意到了一些事情:

  1. 您必须使用Hub 模块来监听signIn 事件。否则,您将无法取回您的用户信息。
  2. 在您的 oauth 配置中,您必须使用 http://localhost:3000/ 定义您的 redirectSignInredirectSignOut (最后的 / 很重要,我是通过艰难的方式才学会的..)
  3. 您可能必须将 ClientIdUserPoolIdconst 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/

相关文章:

amazon-web-services - AWS Cognito 托管 UI - 国际化

javascript - AWS Cognito 和 FB 登录

php - 将多行字符串值提供给 jquery 方法

javascript - 将任意数字替换为变量中的特定数字

javascript - 在将 Canvas 保存为图像之前如何知道渲染是否完成?

javascript - Recharts 2.0.8 <ResponsiveContainer> </ResponsiveContainer> 在 IE11 中不起作用

javascript - React-Router-Redux 分派(dispatch) LOCATION_CHANGE 两次,删除搜索值

javascript - 计数、间隔和事件的响应式扩展缓冲区

javascript - React 中基于 api 调用返回的条件组件

php - AWS cognito 的用途和优势