Reactjs 当会话(存储的cookie)不可访问时,如何保护react路由?
我正在寻找一种有效的方法来防止未经授权的人访问特定的路由路径 我从后端获取的cookie不可读,因此我无法对其进行太多处理。 我有两个端点:Reactjs 当会话(存储的cookie)不可访问时,如何保护react路由?,reactjs,authentication,routing,Reactjs,Authentication,Routing,我正在寻找一种有效的方法来防止未经授权的人访问特定的路由路径 我从后端获取的cookie不可读,因此我无法对其进行太多处理。 我有两个端点: /token(POST)获取带有token的cookie /account(GET)以获取用户名和角色 简要说明我迄今为止所做的工作: 通过使用PrivateRoute组件包装所有路由来保护它们 用户尝试登录后,将触发redux操作。此操作调用一个api,该api返回cookie(jwt)和用户的数据。用户名和角色将保存到“authStore”中。如果登
- 通过使用PrivateRoute组件包装所有路由来保护它们
- 用户尝试登录后,将触发redux操作。此操作调用一个api,该api返回cookie(jwt)和用户的数据。用户名和角色将保存到“authStore”中。如果登录成功,则同一存储中的属性“isAuthenticated”将设置为True。只有当此布尔值设置为true时,用户才能访问包装的路由李>
导出类应用程序扩展了PureComponent{
componentDidMount(){
//检索用户凭据的操作(如果可用,则将其保存到authStore并将isAuthenticated设置为true)
this.props.initloginRequest();
}
render(){
返回(
);
}
}
我通过在index.js(src路径)中调度一个操作解决了这个问题:
import./index.css';
从“./App”导入应用程序;
从“./actions/auth”导入{initloginRequest};
const store=configureStore();
store.dispatch(initloginRequest())
ReactDOM.render(
,
document.getElementById('root'),
);
此操作调用api并检查用户是否经过身份验证。因此,当它到达我的PrivateRoute组件时,它知道应该将用户重定向到哪个方向
在操作完成之前,应将store/state中的isFetching设置为true,以防止App.js呈现路由
export class App extends PureComponent {
render() {
const { isFetching } = this.props
if (isFetching) {
return <div>Loading application...</div>
}
return (
<div className="d-flex flex-column h-100 w-100 bg-grey main-container">
<Sprites className="d-none" />
<Header />
<Switch>
...private route etc...
</Switch>
</div>
);
}
}
export default connect(
(state) => ({
isFetching: state.authStore.isFetching,
}),
(dispatch) => bindActionCreators({
}, dispatch),
)(App);
导出类应用程序扩展了PureComponent{
render(){
const{isFetching}=this.props
如果(正在获取){
返回加载应用程序。。。
}
返回(
…私人路线等。。。
);
}
}
导出默认连接(
(州)=>({
isFetching:state.authStore.isFetching,
}),
(分派)=>bindActionCreators({
},派遣),
)(App);
这应该可以解决问题。你有没有想过这个问题?我面临着一个非常类似的问题,我想知道应该如何处理这个问题。目前,我一直在考虑将一些内部身份验证状态设置为true,然后使用它来处理路由逻辑。对服务器的每一个请求都会包含一个会话cookie,如果没有,服务器将不会返回任何敏感数据,前端内部身份验证状态将设置为false。这听起来不是个好主意,但这是迄今为止我想到的最好的主意:/@zaplec我已经解决了这个问题。请检查我下面的答案。这是否意味着您存储了有关用户是否登录到您的Redux商店的信息?或者这会在每次渲染时进行身份验证检查吗?@zaplec我会在我的redux存储中存储一些用户信息,例如:角色、已验证、名称等。每当页面刷新时,我在index.js中提到的操作都会触发。所以有一次,只要您使用单页应用程序:)
export class App extends PureComponent {
render() {
const { isFetching } = this.props
if (isFetching) {
return <div>Loading application...</div>
}
return (
<div className="d-flex flex-column h-100 w-100 bg-grey main-container">
<Sprites className="d-none" />
<Header />
<Switch>
...private route etc...
</Switch>
</div>
);
}
}
export default connect(
(state) => ({
isFetching: state.authStore.isFetching,
}),
(dispatch) => bindActionCreators({
}, dispatch),
)(App);