← 返回 Skills 市场
bovinphang

Route Protection

作者 Bovin Phang · GitHub ↗ · v2.5.0 · MIT-0
cross-platform ✓ 安全检测通过
39
总下载
0
收藏
1
当前安装
1
版本数
在 OpenClaw 中安装
/install fec-route-protection
功能描述
Use when implementing or reviewing frontend route protection, auth guards, RBAC, permission routes, login state handling, redirects, middleware, React Router...
使用说明 (SKILL.md)

路由保护

Purpose

为前端应用建立清晰的认证、授权和重定向边界,避免越权访问与闪烁渲染。

When to Use

  • 页面需要登录后访问,或不同角色看到不同路由。
  • 需要实现 React Router、Next.js、Nuxt 或 Vue Router 的路由守卫。
  • 登录过期、权限不足、组织/租户切换需要统一处理。
  • 不用于替代服务端授权;前端路由保护只能改善体验,不能作为唯一安全边界。

Procedure

1. 定义认证与授权状态

export type AuthStatus = "loading" | "anonymous" | "authenticated";

export interface CurrentUser {
  id: string;
  roles: string[];
  permissions: string[];
}

export function canAccess(user: CurrentUser, required: string[]) {
  return required.every((permission) => user.permissions.includes(permission));
}

2. React Router 使用布局守卫

import { Navigate, Outlet, useLocation } from "react-router-dom";

interface ProtectedRouteProps {
  requiredPermissions?: string[];
}

export function ProtectedRoute({ requiredPermissions = [] }: ProtectedRouteProps) {
  const location = useLocation();
  const { status, user } = useAuth();

  if (status === "loading") return \x3CRouteLoading />;
  if (status === "anonymous") {
    return \x3CNavigate to="/login" replace state={{ from: location }} />;
  }
  if (requiredPermissions.length > 0 && !canAccess(user, requiredPermissions)) {
    return \x3CNavigate to="/403" replace />;
  }

  return \x3COutlet />;
}
const router = createBrowserRouter([
  {
    element: \x3CProtectedRoute requiredPermissions={["orders:read"]} />,
    children: [{ path: "/orders", element: \x3COrdersPage /> }],
  },
]);

3. Next.js 优先在服务端边界处理

// middleware.ts
import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const token = request.cookies.get("session")?.value;
  const isPrivateRoute = request.nextUrl.pathname.startsWith("/dashboard");

  if (isPrivateRoute && !token) {
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("redirect", request.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"],
};

对需要精细权限的 App Router 页面,在 server component 或 server action 中重新校验权限,不依赖客户端状态。

4. Vue Router / Nuxt 使用导航守卫

router.beforeEach(async (to) => {
  const auth = useAuthStore();
  if (auth.status === "unknown") await auth.fetchCurrentUser();

  if (to.meta.requiresAuth && !auth.user) {
    return { path: "/login", query: { redirect: to.fullPath } };
  }

  const required = to.meta.permissions as string[] | undefined;
  if (required?.length && !auth.canAccess(required)) {
    return { path: "/403" };
  }
});

5. 统一失败与跳转体验

  • 401:清理过期会话,跳转登录页并保留 redirect
  • 403:进入无权限页,不反复重试。
  • loading:渲染稳定骨架屏,避免先显示私有内容再跳转。
  • 登录成功:只跳转到同源且允许的路径,防止 open redirect。
  • RBAC:权限矩阵来自可信会话或后端返回;前端只用于路由体验和 UI 裁剪,不能替代接口授权。
  • 会话刷新:401 刷新失败后统一清理状态;避免多个并发请求各自触发跳转或刷新风暴。

Constraints

  • 前端路由保护不是安全边界;API、SSR loader、server action 必须重复做授权校验。
  • 不要在组件渲染后用 useEffect 才跳转私有页面,否则会出现敏感内容闪烁。
  • redirect 参数必须限制为站内路径,不能直接信任 URL 输入。
  • 权限信息应来自可信会话或后端响应,不要只依赖 localStorage 中的角色字段。
  • 多租户应用必须把 tenant/org 上下文纳入权限判断。
  • 不把菜单隐藏视为授权完成;用户直接访问 URL、刷新页面、篡改 localStorage 和替换 tenant 都必须验证。

Expected Output

产出一套路由守卫实现,覆盖 loading、未登录、权限不足、登录后回跳和会话过期。验证时直接访问私有 URL、刷新页面、切换角色、篡改 redirect 参数,确认行为稳定且 API 仍有服务端授权。

安全使用建议
This skill appears safe to install as a reference guide. Treat its code snippets as examples to adapt and still enforce authorization on APIs, loaders, server actions, and backend routes.
能力评估
Purpose & Capability
The skill’s purpose is coherent: it guides implementation and review of frontend route guards, RBAC checks, redirects, and related auth patterns. The included examples are aligned with that purpose.
Instruction Scope
Instructions are scoped to frontend security design and explicitly warn that frontend route protection is not a substitute for server-side authorization.
Install Mechanism
The artifact contains only SKILL.md, README.md, metadata.json, and package.json. No install scripts, executable files, or runtime hooks are present.
Credentials
No API keys, tokens, local profiles, browser sessions, or external service credentials are requested.
Persistence & Privilege
No persistence, background workers, privilege escalation, file mutation, network automation, or account-impacting actions are defined.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install fec-route-protection
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /fec-route-protection 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.5.0
Version 2.5.0 - Expanded documentation in SKILL.md with detailed guidance for frontend route protection across React Router, Next.js, Vue Router, and Nuxt. - Added clear definitions for authentication states, RBAC, and permission checks. - Provided practical code examples for server-side and client-side route guards. - Clarified security constraints, best practices, and failure-handling patterns. - Emphasized the distinction between frontend protection and true server-side authorization.
元数据
Slug fec-route-protection
版本 2.5.0
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 1
常见问题

Route Protection 是什么?

Use when implementing or reviewing frontend route protection, auth guards, RBAC, permission routes, login state handling, redirects, middleware, React Router... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 39 次。

如何安装 Route Protection?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install fec-route-protection」即可一键安装,无需额外配置。

Route Protection 是免费的吗?

是的,Route Protection 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Route Protection 支持哪些平台?

Route Protection 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Route Protection?

由 Bovin Phang(@bovinphang)开发并维护,当前版本 v2.5.0。

💬 留言讨论