简体   繁体   中英

Is it safe to use conditional rendering in react-router-dom for authentication

In the code below:

If user auth data which sent from ClientSide , matches in backend , backend sends response with user id , in front setIsAuth sets true then Layout Component sends first <Switch> case and the client can reach any protected Components.Otherwise, setIsAuth sets false then Layout Component sends second <Switch> case which includes only <Signup /> and <Login /> routes.Is it safe way for authentication?


  let [isAuth, setIsAuth]=useState( false )

  return (
    <>
      {
       isAuth ? <Switch>
        <Route exact path={"/"} component={ Home } />

        <Route exact path={"/shopping-card"} component={ShoppingCard} />
        <Route exact path={"/order-success"} component={ OrderSuccess } />
        <Route exact path={"/orders"} component={ Orders } />
        <Route exact path={"/products"} component={ Products } />

        <Redirect to={"/user/login"} />
      </Switch> : <Switch>
        <Route exact path={"/user/signup"} component={ Signup } />
        <Route exact path={"/user/login"} component={ Login } />

        <Redirect to={"/user/login"} />
      </Switch>
      }
    </>
  )
}

export default Layout

For the code shown , yes. Because the code shown has no sensitive information. What you're doing in the code shown is presenting two different interfaces based on whether the user is authenticated.

The real question you need to ask yourself is what information is sent to the client for an unauthenticated user. Do these components contain sensitive information? If so, conditionally hiding/showing them makes no difference. The information has already been sent to the client, so the client has it.

Changing the UI based on authentication is fine to do client-side. But showing/hiding sensitive information should always be server-side , since determining that client-side would involve sending that information to the client before making that determination. (And would involve making that determination on the client, which is inherently insecure.)

As long as the actual sensitive information requires providing authentication/authorization to the server to get that data in response, all you're doing in the client-side code is presenting a user experience. Even if a user were to modify that, they wouldn't be able to get any sensitive information without interacting with the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM