2015-10-01 125 views
52

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

我用反应路由器的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

https://github.com/rackt/react-router/tree/master/examples/auth-flow你怎么虽然检查?从一个cookie?从服务器调用?我认为它通常是在'Route'的'onEnter'中完成的,而不是'componentWillMount'。 onEnter = {function(nextState,transition){if(!USER_IS_AUTHED){transition.to('login'); }})}' – Dylan

回答

53

阵营路由器V4更新的解决方案

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

阵营路由器最多V3

使用“的OnEnter”事件,并在回调检查,如果用户被授权:

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

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

在示例和文档方面情况有所恶化。 “auth-flow”示例对我来说不起作用,并且找到有关处理程序的第二个参数应该接受的信息并不容易,所以我可以尝试不同的方法。 – backdesk

+0

onEnter(nextState,replace,callback?) “当路由即将被输入时调用它提供下一个路由器状态和*一个函数*来重定向到另一个路径,这将是触发挂钩的路由实例“。 – backdesk

+0

你能指出文档和版本我会进行更新吗? – Pawel

5

有了反应,路由器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> 
    ); 
    } 
}); 

在文档,它们显示another way to do it,通过使用render财产,而不是component。他们定义了一个PrivateRoute,当您定义所有路由时,它使代码非常明确。

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') 
}