I'm building a react application using node and express back-end. I've used JWT and passport for Authentication. So when ever i login in it returns the authorization token.So now the back-end endpoints could be accessed with the token.But i don't know how to restrict the user from moving to other routes(react-routes) when the users are not logged in tho the system.And i have tested the endpoints using using postman,to access the endpoints im using axios. The token in currently saved in the local storage of the browser, how can i send the token along with axios rest calls?
0
votes
1 Answers
0
votes
Found it!. I dont have to control from back-end instead i can use onEnter prop in reeact router to use with a middle-ware to check for a certain authentication. if it returns true it will move to your route or else it would move to your default rout mentioned. the code is below.
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
render((
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="login" component={Login} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth}/>
</Router>
), document.getElementById('example'))