0

我使用 Okta 对我的 React Web 应用程序进行了身份验证,但是如果用户未通过身份验证或令牌过期,那么它会将用户重定向到该/login页面。

Page1.js:

import React, { useState, useEffect } from "react";
import { useOktaAuth } from "@okta/okta-react";
import { Redirect, useHistory } from "react-router-dom";

const { authState } = useOktaAuth();
const history = useHistory();

useEffect(() => {
    if (!authState) {
      history.push("/login");
    }
});

有没有一种方法可以将上述内容包含到一个可以导入到每个不同 Page[#].js 的函数中,而不是在每个文件中包含上面的代码?

只是试图重构并确保我的代码在我去的时候是整洁的,但不确定解决这个问题的最佳方法。

蒂亚!

4

2 回答 2

0

你可以使用下面的

私有路由组件

import React, { useEffect } from 'react';
import { Route, Redirect, RouteProps, useHistory } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from 'app/config/store';
import { SecureRoute, useOktaAuth } from '@okta/okta-react';
import { authenticationSuccess } from '../reducers/authentication-slice';

export const PrivateRouteComponent = ({ component: Component, ...rest }: IOwnProps) => {
//reducer 
  const isAuthenticated = useAppSelector(state => state.authentication.isOktaAuthenticated);
  const { authState, oktaAuth } = useOktaAuth();

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (!isAuthenticated && authState && authState.isAuthenticated) {
      oktaAuth.token.getUserInfo().then(info => {
//action dispatch
        dispatch(authenticationSuccess({ name: info.name, email: info.email }));
      });
    }
  }, [authState, oktaAuth]); // Update if authState changes

  const renderRedirect = props => {
    return isAuthenticated && <Component {...props} />;
  };

  return <SecureRoute {...rest} render={renderRedirect} />;
};

export default PrivateRouteComponent;

在 app.js 中

 <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
      <Switch>
            <Route path="/callback" component={LoginCallback} />
            <PrivateRoute path="/" exact={true} component={Home} />
            <PrivateRoute path="/home" exact={true} component={Home} />
      </Switch>
  </Security>
于 2021-07-13T13:30:51.280 回答
0

您可以将需要用户登录的所有组件包装在一个组件中并保护路由。

用户登录后,在 localstorage 或 redux 中设置一个令牌(您需要将其持久化)。指定通过 IsloggedIn 组件的路由,这样,这些路由只有在用户登录时才能访问,否则将被重定向到登录页面

例子

import React from "react";
import { Redirect, Route } from "react-router-dom";

function IsLoggedIn({ Component, ...props }) {

  const isAuthenticated = localStorage.getItem("isAuthenticated");

  return (
    <Route {...props}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
}

export default IsLoggedIn;

在 App.js 中

function App(){
  return(
    <BrowserRouter>
       <Route exact path="/login" component={Login} />
       <IsLoggedIn exact path="/" component={Page1} />
    </BrowserRouter>
  )
}
于 2021-07-12T09:45:30.077 回答