【发布时间】:2020-04-09 13:36:42
【问题描述】:
我有一个使用 Auth0 的经过身份验证的 React 应用程序,我正在尝试实现一个路由 (/paywall),它在我的索引页面 ("/") 顶部呈现一个带有内容的模式。我以官方的 React Router 文档为例(https://reacttraining.com/react-router/web/example/modal-gallery),但是每当我将 location 属性添加到我的组件时,我的应用程序就会中断。它在我的 /callback 路由上挂断并且永远不会进行身份验证 - 我已经找到了我所有的位置道具,它们似乎都正确通过了。
我的带有 Switch 的应用:
const location = useLocation();
const background = location.state && location.state.background;
return (
<Router>
<Switch location={background || location}>
<Route
exact
path="/"
render={props => {
return (
<SecuredRoute
component={Dashboard}
source={source}
auth={auth}
{...props}
/>
);
}
/>
<Route path="/paywall" children={<h1>PAYWALL</h1>} />
</Switch>
{background && <Route path="/paywall" children={<Modal />} />}
</Router>
)
来自官方 Auth0 示例的任何我的 SecuredRoute 组件:
export default ({ component: Component, auth, source, ...rest }) => {
const isAuthenticated = auth.isAuthenticated();
const isEmailVerified = auth.isEmailVerified();
const isPhoneVerified = auth.isPhoneVerified;
if (isAuthenticated === true && (isEmailVerified === true || isPhoneVerified === true)) {
if (auth.checkSource(source.sourceId) === false) {
return <Redirect to={{ pathname: '/whereami' }} />;
}
auth.pollAuthenticated(rest.location);
return (
<div className="container">
<Component auth={auth} source={source} {...rest} />
</div>
);
}
return <Redirect to={{ pathname: '/callback', state: { referrer: rest.location || '' } }} />;
};
还有我的回调组件:
// Render Component
const Callback = props => {
const handleAuthentication = location => {
if (/access_token|id_token|error/.test(location.hash)) {
props.auth.handleAuthentication();
} else {
let referrer = '/';
if (location.state && location.state.referrer) {
referrer = location.state.referrer.pathname;
}
props.auth.checkSession(referrer);
}
};
handleAuthentication(props.location);
return <Spinner fullscreen />;
};
【问题讨论】:
标签: reactjs react-router auth0