簡體   English   中英

反應路由器授權

[英]React Router Authorization

在組件安裝之前進行授權檢查的最佳做法是什么?

我使用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>
    );
  }
});

針對React路由器v4的更新解決方案

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

使路由器達到v3

使用'onEnter'事件並在回調中檢查用戶是否獲得授權:

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

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

使用react-router 4,您可以訪問組件內的Route道具 要重定向用戶,您只需將新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 ,當您定義所有路由時,它會使代碼非常明確。

如果您想對多個組件應用授權,那么您可以這樣做。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM