首页 > 解决方案 > ReactJS:全局 Okta 身份验证辅助函数

问题描述

我使用 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 的函数中,而不是在每个文件中包含上面的代码?

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

蒂亚!

标签: javascriptreactjsokta-signin-widget

解决方案


你可以使用下面的

私有路由组件

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>

推荐阅读