我正在尝试使用 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
,它会路由到其他组件页面。不过,我不确定在这种情况下它会起作用吗?