Разрешить авторизацию маршрутизатора
Каковы наилучшие методы проверки авторизации перед установкой компонентов?
Я использую реактивный маршрутизатор 1.x
Вот мои маршруты
React.render((
<Router history={History.createHistory()}>
<Route path="/" component={Dashboard}></Route>
<Route path="/login" component={LoginForm}></Route>
</Router>
), document.body);
Вот мой компонент Dashboard:
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>
);
}
});
Ответы
Ответ 1
Обновленное решение для
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) => { ... }
Ответ 2
В режиме взаимодействия с маршрутизатором 4 у вас есть доступ к реквизитам маршрута внутри компонента. Чтобы перенаправить пользователя, вам просто нужно нажать новый 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
. Они определяют PrivateRoute
, что делает код очень явным, когда вы определяете все свои маршруты.
Ответ 3
Если вы хотите применить авторизацию для нескольких компонентов, вы можете сделать это следующим образом.
<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')
}