首页 > 解决方案 > 登录/注册 AWS Cognito React 的安全页面

问题描述

我正在为应用程序创建登录/注册页面,并且我是第一次使用 AWS Cognito 和 React。在有人登录/注册之前,我需要保护我的页面。我不知道如何将 userAuth() 中的任何内容发送到导出默认值,或者如何使其工作。

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from 'react-router-dom';
import App from '../App';
import { Auth } from 'aws-amplify';
//last thing 333

async function userAuth() {
  let something = Boolean;
  Auth.currentSession()
    .then(function(fulfilled) {
      console.log('worked' + fulfilled);
      something === true;
      return something;
    })
    .catch(function(error) {
      console.log('didnt work' + error);
      window.location.href = '/';
      return error;
    });
}
export default ({ component: C, ...rest }) => (
  alert('this is the user auth ' + userAuth()),
  (
    <Route
      {...rest}
      render={
        props =>
          userAuth() === 'something' ? (
            <Redirect to="/" />
          ) : (
            <C {...props} />
          )
      }
    />
  )
);

标签: javascriptreactjsamazon-cognito

解决方案


Auth.currentAuthenticatedUser()是一个异步 API,所以你不能从这个 API 返回任何可以在 a 中使用的东西Route(有可能返回 a Promise,但这实际上不是必需的。)

您可以将组件更改为class类似:

class PrivateRoute extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      authStatus: false,
      loading: false,
    }
  } 
  componentDidMount() {
    Auth.currentAuthenticatedUser()
      .then((user)=> {
        this.setState({ loading: false, authStatus: true });
      })
      .catch(() => {
        this.setState({ loading: false });
        this.props.history.push('/login');
      });
  }
  render() {
    return <Route {...rest} render={(props) => (
       this.state.authStatus
         ? <Component {...props} />
         : <div>Loading ... </div>
    )} />
  }
}

推荐阅读