【发布时间】:2016-11-11 07:56:26
【问题描述】:
在我的应用程序中,我拥有管理员页面的权限,登录后我只想授予拥有此权限的用户访问此页面的权限。
在应用程序启动之前,有什么方法可以使用 ajax 为组件加载路由? 在某些操作(如登录)之后有什么方法可以更改组件的路由吗? 解决此问题的最佳做法是什么?
【问题讨论】:
标签: reactjs react-router react-redux react-router-redux
在我的应用程序中,我拥有管理员页面的权限,登录后我只想授予拥有此权限的用户访问此页面的权限。
在应用程序启动之前,有什么方法可以使用 ajax 为组件加载路由? 在某些操作(如登录)之后有什么方法可以更改组件的路由吗? 解决此问题的最佳做法是什么?
【问题讨论】:
标签: reactjs react-router react-redux react-router-redux
react-router 存储库中有一个 example。他们使用onEnter 属性来检查授权:
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="/" component={App}>
<Route path="login" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>
onEnter 属性是一个在进入路由之前调用的函数:
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
onEnter 函数具有以下调用签名:
onEnter(nextState, replace, callback?)
这使您可以访问状态以检查用户是否具有管理员权限。
另一种经常讨论的方法是使用高阶组件。需要管理员权限的组件不需要知道这一点,而是由限制访问的组件包装。
更多信息:
https://blog.tighten.co/react-101-routing-and-auth
https://github.com/joshgeller/react-redux-jwt-auth-example
https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/
与往常一样,客户端是不可信任的,数据应该在服务器上得到保护。
【讨论】: