I
I
Ilya Livshits2016-10-03 16:13:21
User identification
Ilya Livshits, 2016-10-03 16:13:21

React, Router and Authentication. How best to implement?

Hello. I have SPA on react and router. There is a REST service for authentication. But how to make it safe? I can make a direct request to this service from the client, and in case of successful authorization, I will be allowed to go to the page I need, if not, then redirect. But this is not safe, because you can simply go directly to the desired page. Tell me please?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Gromov, 2016-10-03
@Pathgk

This page is not static and is entirely contained in the build, but is built according to the data received on the request corresponding to it? If so, then this request should check the session or token on the server, which are set by the service for authentication. And in case of lack of rights instead of information on the page, display an error. If not, please provide details.

M
Maxim, 2016-10-03
@maxfarseer

The task can be divided into 2 parts:
1) getting a token (session ID or whatever else is needed) from the service.
2) onEnter hook in the router
Sample code:

export default function configRoutes(store) {
  function _ensureAuthenticated(nextState, replace, callback) {
    const { dispatch } = store 
    const { session } = store.getState()
    const { currentUser } = session

    if (!currentUser && localStorage.getItem('token')) {
      dispatch(getCurrentAccount())
    } else if (!localStorage.getItem('token')) {
      replace('/signin')
    }

    callback()
  }

  return (
    <Route component={App}>
      <Route path='/signin' component={SigninContainer} />
      <Route path='/signup' component={SignupContainer} />

      <Route path='/' component={AuthenticatedContainer} onEnter={_ensureAuthenticated}>
        <Route component={ReportContainer}>
          <Route path='/activities' component={ActivitiesContainer} />
          <Route path='/activities/:id' component={CaptionsContainer} />
        </Route>
      </Route>

    </Route>
  )
}

More details can be found in the source . The ConfigRoutes function is called here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question