首页 > 解决方案 > 使用 AWS Cognito 反应受 Redux 保护的路由

问题描述

我正在尝试使用 React Redux 和 AWS Cognito 呈现带有侧边栏的主页,该侧边栏将用户重定向到相关端点。在这方面,必须为 Cognito 使用 AWS 回调让我感到困惑。这是应用程序:

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Callback from "./routes/Callback";
import { Home } from "./routes/Home";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

const App = () => (
  <Router history={history}>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route exact path="/callback" component={Callback} />
    </Switch>
  </Router>
);

export default App;

现在是Home组件,成功登录后用户将被重定向到该组件(我正在使用 Redux):

import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import cognitoUtils from "../lib/cognitoUtils";
import appConfig from "../config/app-config.json";

export const Home = () => {
  const session = useSelector((state) => state.session);

  const onSignOut = (e) => {
    e.preventDefault();
    cognitoUtils.signOutCognitoSession();
  };

  return (
    <div>
      {session.isLoggedIn ? (
        <div>Logged In</div>
      ) : (
        <div>
          <p>You are not logged in.</p>
          <a className="Home-link" href={cognitoUtils.getCognitoSignInUri()}>
            Sign in
          </a>
        </div>
      )}
    </div>
  );
};

这是我的Callback功能:

import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import { initSessionFromCallbackURI } from '../actions/session'

function mapStateToProps (state) {
  return { session: state.session }
}
function mapDispatchToProps (dispatch) {
  return {
    initSessionFromCallbackURI: href => dispatch(initSessionFromCallbackURI(href))
  }
}

class Callback extends Component {

  componentDidMount () {
    if (this.props.location.hash || this.props.location.search) {
      this.props.initSessionFromCallbackURI(window.location.href)
    }
  }

  render () {
    if ((!this.props.location.hash && !this.props.location.search) || this.props.session.isLoggedIn) {
      return <Redirect to="/" />
    }

    return <div />
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Callback)

最后是启动会话的操作:

import { CLEAR_SESSION, SET_SESSION } from "../constants/actionTypes";
import cognitoUtils from "../lib/cognitoUtils";

export const clearSession = () => ({
  type: CLEAR_SESSION,
});

// Initialise the Cognito sesson from a callback href
export function initSessionFromCallbackURI(callbackHref) {
  console.log("callbackHref is: " + callbackHref);
  return function (dispatch) {
    return cognitoUtils
      .parseCognitoWebResponse(callbackHref) // parse the callback URL
      .then(() => cognitoUtils.getCognitoSession()) // get a new session
      .then((session) => {
        dispatch({ type: SET_SESSION, session });
      });
  };
}

export const setSession = (session) => ({
  type: SET_SESSION,
  session,
});

通常,如果没有回调,我会PrivateRoute在应用程序本身中创建一个组件,并可能在Sidebar那里创建一个路由到其他组件页面的组件。我不确定它在这种情况下会起作用吗?

标签: javascriptreactjsreact-reduxreact-routersidebar

解决方案


推荐阅读