Home > Blockchain >  React JS - How do I prevent users from tampering their cookies and gaining access to protected route
React JS - How do I prevent users from tampering their cookies and gaining access to protected route

Time:11-22

I have a React app wherein the user object is stored as cookies in the App component. This user object has a property AccountType which is an integer, and 1 means that the user is a student and 2 means the user is a teacher.

I am using react-router v5 to protect certain routes from being accessed, unless the logged in user is of AccountType 2 (teacher) with the following RouteGuard component:

const RouteGuard = ({ component: Component, ...rest }) => {
  const user = JSON.parse(Cookies.get("loggedInUser"));
  
  return (
    <Route
      {...rest}
      render={(props) => {
        return user.AccountType === 2 ? (
          <Component />
        ) : (
          <Redirect
            to={{
              pathname: "/403",
              state: {
                error: "You are not allowed to access this resource.",
                from: props.location.pathname,
                redirected: true,
              },
            }}
          />
        );
      }}
    />
  );
};

And an example of how this RouteGuard component is used:

    <Switch>
      <RouteGuard path="/records" exact component={Records} />
    </Switch>

It works well, for normal cases, but I found out that I can login as a student and go to the developer console and in the cookies section, I can modify the cookies and manually set AccountType to 2, thereby bypassing the route protection.

What would be the proper way of preventing unauthorized users from tampering cookies and gaining access to protected endpoints, front-end wise?

CodePudding user response:

There is no way to disallow this. The best method would be to store a version of any username in the local storage, then compare that data to a server-side database to figure out if that user has the required account type.

This is a similar question: How to secure localStorage in HTML5?

CodePudding user response:

If you get this value from the backend and store it in local storage it will solve your problem. But The best approach will be authenticate using the JWT token and pass the necessary info into it.

  • Related