如何在reactjs中实现用户访问控制,根据后端链接或url使用路由

ktecyv1j  于 2023-03-31  发布在  React
关注(0)|答案(1)|浏览(150)

如何在reactjs web应用中使用路由实现用户访问控制。
从后端,我得到所有的网址,这是可访问的登录用户。
例如,如果user1已登录,而我从后端获取的数据

{
  0: {
    name: 'Homes', 
    uri: 'home', 
    menus: [
      0: { uri: 'home/dashboard', name: 'Dashboard' }
      1: { uri: 'home/people', name: 'People' }
      2: { uri: 'home/subject', name: 'Subject' }
    ]
  }

如果另一个用户登录了我从后端获取的数据

0: {
    name: 'Homes', 
    uri: 'home', 
    menus: [
    0: { uri: 'home/dashboard', name: 'Dashboard' }
  ]
}

General Routing which I have already done:

<Router>
  <Routes>
   <Route path = '/home' element={<Users />} 
     <Route path = 'dashboard' element={<Dashboard />} />
     <Route path = 'people' element={<People />} />
     <Route path = 'subject' element={<Subject />} />
   />

  </Routes>
</Router>
6ojccjat

6ojccjat1#

你可以创建一个protected route组件,它读取接收到的后端数据对象,并将其与当前访问的路由路径进行比较。这是一个使用React上下文提供用户数据值并将Users组件重构为路由保护组件的示例,因为它是嵌套用户子路由的布局路由。

const UserContext = createContext({
  user: null
});

const useUserContext = () => useContext(UserContext);

const UserContextProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  ... Logic to set/clear the fetched user route access data

  return (
    <UserContext.Provider value={{ user }}>
      {children}
    </UserContext.Provider>
  );
};
<Routes>
  ...
  <Route path="/home" element={<Users />}>
    <Route path="dashboard" element={<Dashboard />} />
    <Route path="people" element={<People />} />
    <Route path="subject" element={<Subject />} />
    ...
  </Route>
  ...
</Routes>
const Users = () => {
  const { pathname } = useLocation();
  const { user } = useUserContext();

  const canAccessRoute = user?.menus.some(({ uri }) => uri === pathname);

  ...

  return canAccessRoute ? (
    <>
      ... Users UI ...
      <Outlet />
    </>
  ) : (
    <Navigate to="/" replace />
  );
};

相关问题