mdmb
mdmb

Reputation: 5283

Handling JWT authentication in React app

I'm trying to implement a restricted route with react-router v4 and I'm almost done, but I need to handle validation of JWT token and don't know where to put this.

RestrictedRoute

const RestrictedRoute = (props) => {
  const { component, ...otherProps } = props;
  return <Route {...otherProps} component={component} />;
};

const mapStateToProps = state => ({
  authenticated: state.authentication.session,
});


const branched = branch(
  ({ authenticated }) => !authenticated,
  renderComponent(() => <Redirect to="/login" />),
);

const enhanced = compose(
  connect(mapStateToProps),
  branched,
)(RestrictedRoute);

export default enhanced;

So with this I'm able to redirect users to /login page if the state.authentication.session is set to false. Until now I was checking if there is a jwt cookie and setting this session based on that. This had some simple vulnerability as you could add jwt cookie with any value, and you will be considered as authenticated.

I created an endpoint for validating my jwt token and created an action for this. My question is - where to put this?

If I put this in componentWillMount of RestrictedRoute and a authenticated user tries to visit a restricted page he is showed the login page and then switched to the restricted route, as the response from the endpoint changes the redux store.

Upvotes: 0

Views: 652

Answers (1)

hossein derakhshan
hossein derakhshan

Reputation: 771

do you want to validate your token in each of your RestrictedRoute? why?!

you don't need to validate your token for changing a route even if your react -route is restricted.

you have to validate your token for getting data on the server by write a policy or middle-ware for that API.

with this method you can just checking a cookie for validate it in react-route.. if hackers put the data on your cookie, they can access to that react-route but they cant see the data

Upvotes: 1

Related Questions