【问题标题】:AmplifyAuthenticator with react-router-domAmplifyAuthenticator 与 react-router-dom
【发布时间】:2021-08-18 19:05:10
【问题描述】:

我正在构建一个 React JS 应用程序,我想使用 AWS Amplify 的 AmplifyAuthenticator 轻松保护我使用 react-router-dom 配置的路由。我过去使用过 Amplify 的 withAuthenticator,但我想确保将来可以灵活地自定义身份验证...因此我使用 AmplifyAuthenticator

我已将受保护的路由包装在 <AmplifyAuthenticator> 组件中,它似乎工作正常,但我想确保这是一种可靠的方法。我的代码看起来像这样:

import React, { useCallback, useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { AmplifySignOut, AmplifySignIn, AmplifyAuthenticator } from '@aws-amplify/ui-react';
import LandingPage from './components/LandingPage';
import ProtectedPage from './components/ProtectedPage';
import Navigation from './components/Navigation';

function App() {

  return (
    <Router>
      <Navigation />
      <Switch>
        <Route path="/" exact component={LandingPage}/>
        <Route path="/LangingPage" component={LangingPage}/>
        <AmplifyAuthenticator>
          <Route path="/protected" component={ProtectedPage}/>
        </AmplifyAuthenticator>
      </Switch>
    </Router>
  );
}

export default App;

这是保护这些路线的有效方法吗?非常感谢!

【问题讨论】:

    标签: reactjs react-router react-router-dom aws-amplify


    【解决方案1】:

    将 Route 包装到 PrivateRoute:

        // A wrapper for <Route> that redirects to the login
        // screen if you're not yet authenticated.
        function PrivateRoute({ children, ...rest }) {
          let auth = useAuth();
          return (
            <Route
              {...rest}
              render={({ location }) =>
                auth.user ? (
                  children
                ) : (
                  <Redirect
                    to={{
                      pathname: "/login",
                      state: { from: location }
                    }}
                  />
                )
              }
            />
          );
        }
    

    https://codesandbox.io/s/react-router-redirects-auth-xb8qq?from-embed=&file=/example.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2018-02-25
      • 2017-10-04
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多