React鉴权

React项目的登录/权限验证实现

Posted by page on August 27, 2024

React鉴权

登录验证

登录状态

context实现

import { UserProvider } from "@/context/user.tsx";

export default function App() {
  return (
    <UserProvider>
      <Router></Router>
    </UserProvider>
  );
}

context/UserContext.tsx

import { useAuthState } from "@/hooks/useAuthState.ts";

import type { User } from "firebase/auth";

export const UserContext = createContext<User | null>(null);

export const UserProvider = ({ children }: { children: React.ReactNode }) => {
  const user = useAuthState();
  return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};

鉴权守卫

@/router/components/AuthGuard.tsx

import { UserContext } from "@/context/user.tsx";

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const user = useContext(UserContext);
  if (!user) return <Navigate to="/login" replace />;
  return children;
}

使用:在routes中为内页添加鉴权守卫

// @/router/index.tsx

const LoginRoute: RouteObject = {
  path: "/login",
  // login页不需要鉴权
  element: lazyLoad(lazy(() => import("@/pages/login/login.tsx"))),
};

// 后台内页需要鉴权
const adminRoutes: RouteObject = {
  path: "/",
  element: (
    <AuthGuard>
      <Outlet />
    </AuthGuard>
  ),
  children: [
    {
      index: true,
      element: lazyLoad(lazy(() => import("@/pages/home/home.tsx"))),
    },
    // ... permissionRoutes
  ],
};

export default function Router() {
  const routes: RouteObject[] = [adminRoutes, LoginRoute, ...];
  const router = createHashRouter(routes);
  return <RouterProvider router={router} />;
}