Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - How do I protect a path in React?

I followed this page to create a React application and it worked fine.

However, when I added the following link:

 <li>
     <Link to='/protected/gg'>
         Link to Protected Page GG
     </Link>
 </li>

The word "GG" is shown without login when I browse the path /protected/gg.

It seems that the GuardedRoute can protect /protected path only.

So, is it possible to protect everything under /protected folder?

If so, would you tell me how to do so? Or give me a keyword so that I can google the solution.

Stackblitz of my work

question from:https://stackoverflow.com/questions/65897499/how-do-i-protect-a-path-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Similar to other answer, but IMO a little simpler.

While you could just define a flat list of routes, some guarded and some not, you could create "walled guardens" (see what I did there).

Modify your GuardedRoute to conditionally render a Route or Redirect, passing all the other props through.

const GuardedRoute = ({ auth, ...rest }) => {
  return auth ? <Route {...rest} /> : <Redirect to="/" />;
};

Then simply make a "guarded" section in your router. Remember that order of routes within a Switch component matter, so order more specific paths before *less specific paths.

<Switch>
  <Route exact path="/" component={Home} />
  <GuardedRoute path="/protected" auth={isAutheticated}>
    <Switch>
      <Route path="/protected/gg" component={GG} />
      <Route path="/protected" component={Protected} />
    </Switch>
  </GuardedRoute>
  <Route path="/unprotected" component={Unprotected} />
</Switch>

I typically use codesandbox, but let me know if this forked stackblitz fails to load.

https://react-mjyp8g.stackblitz.io


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...