反应路由器授权

时间:2015-10-01 23:18:27

标签: javascript reactjs authorization react-router

在安装组件之前进行授权检查的最佳做法是什么?

我使用react-router 1.x

这是我的路线

React.render((
  <Router history={History.createHistory()}>
    <Route path="/" component={Dashboard}></Route>
    <Route path="/login" component={LoginForm}></Route>
  </Router>
), document.body);

这是我的仪表板组件:

var Dashboard = React.createClass({
  componentWillMount: function () {
    // I want to check authorization here
    // If the user is not authorized they should be redirected to the login page.
    // What is the right way to perform this check?
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});

3 个答案:

答案 0 :(得分:60)

更新了解决方案 React router v4

<Route 
  path="/some-path" 
  render={() => !isAuthenticated ?
    <Login/> :
    <Redirect to="/some-path" />
}/>

将路由器设置为v3

使用'onEnter'事件并在回调中检查用户是否获得授权:

<Route path="/" component={App} onEnter={someAuthCheck}>  

const someAuthCheck = (nextState, transition) => { ... }

答案 1 :(得分:5)

使用react-router 4,您可以访问组件内的Route props。要重定向用户,您只需将新URL推送到历史记录即可。在您的示例中,代码为:

var Dashboard = React.createClass({
  componentWillMount: function () {
    const history = this.props.history; // you'll have this available
    // You have your user information, probably from the state
    // We let the user in only if the role is 'admin'
    if (user.role !== 'admin') {
      history.push('/'); // redirects the user to '/'
    }
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});

在文档中,他们使用render属性而非component显示another way to do it。它们定义了PrivateRoute,当您定义所有路径时,它会使代码非常明确。

答案 2 :(得分:0)

如果您想对多个组件应用授权,那么您可以这样做。

<Route onEnter={requireAuth} component={Header}>
    <Route path='dashboard' component={Dashboard} />
    <Route path='events' component={Events} />
</Route>

对于单个组件,您可以

<Route onEnter={requireAuth} component={Header}/>

function requireAuth(nextState, replaceState) {
  if (token || or your any condition to pass login test)
  replaceState({ nextPathname: nextState.location.pathname }, 
  '/login')
}