developer tip

React Router 인증

optionbox 2020. 12. 9. 08:04
반응형

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 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) => { ... }

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

문서 에서는 대신 속성 을 사용하여 다른 방법을 보여줍니다 . 그들은 정의 귀하의 모든 경로를 정의 할 때, 그 코드가 매우 명시합니다.rendercomponentPrivateRoute


If you want to apply authorization on multiple components then you can do it like this.

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

For single component you can do

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

참고URL : https://stackoverflow.com/questions/32898264/react-router-authorization

반응형