【问题标题】:ReactJS: Global Okta Auth Helper FunctionReactJS:全局 Okta 身份验证辅助函数
【发布时间】:2023-04-01 14:35:02
【问题描述】:

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

我只是尝试重构并确保我的代码在执行过程中保持整洁,但不确定解决这个问题的最佳方法。

TIA!

【问题讨论】:

    标签: javascript reactjs okta-signin-widget


    【解决方案1】:

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

    一旦用户登录,在 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>
      )
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用下面的

      私有路由组件

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2022-09-29
        • 2021-01-11
        • 2021-03-14
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        相关资源
        最近更新 更多