javascript - 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 的函数中,而不是在每个文件中包含上面的代码?
只是试图重构并确保我的代码在我去的时候是整洁的,但不确定解决这个问题的最佳方法。
蒂亚!
解决方案
你可以使用下面的
私有路由组件
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>
推荐阅读
- excel - 当我没有选择多个范围时,为什么会收到运行时间错误 1004?
- tensorflow - Keras 自定义损失函数打印张量值
- python - 根据下一列熊猫中的重复范围迭代列值
- prestashop - Prestashop:显示来自主题/主题名称/资产/img 文件夹的图像不起作用
- javascript - 无法从服务订阅数据到组件
- azure - 从 VSTS 管道获取值##debug
- automation - 低功耗蓝牙设备触发 Web 服务调用
- javascript - 将 setTimeout 转换为 async awesomeness?
- javascript - 无法使 Gtranslate 语言在下拉列表中工作
- c# - 如何调整 Syncfusion 图表的水平线注释的文本颜色?