Loading...
Loading...
使用 @aptx/api-plugin-csrf 添加 CSRF 保护。触发条件:当代码需要在请求中添加 CSRF token、配置 cookie/header 名称、处理 SSR/Node 环境的 cookie 读取、或使用 createCsrfMiddleware 时使用。
npx skill4agent add haibaraaiaptx/aptx-skill aptx-api-plugin-csrfcreateCsrfMiddleware({ cookieName, headerName, sameOriginOnly, getCookie })getCookiedocument.cookiegetCookiesameOriginOnly: trueRequestClient.use()@aptx/api-core| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | CSRF cookie 名称 |
| | | 写入 CSRF token 的 header 名称 |
| | | 仅在同源请求中附加 token |
| | 浏览器默认使用 | 自定义 cookie 读取函数(SSR 必须提供) |
| 场景 | 添加 token |
|---|---|
Cookie 存在 + | ✅ |
Cookie 存在 + | ✅ |
Cookie 存在 + | ❌ |
| Cookie 不存在 | ❌ |
import { RequestClient } from "@aptx/api-core";
import { createCsrfMiddleware } from "@aptx/api-plugin-csrf";
const client = new RequestClient({
middlewares: [
createCsrfMiddleware({
cookieName: "XSRF-TOKEN",
headerName: "X-XSRF-TOKEN",
sameOriginOnly: true,
// 浏览器环境下不需要 getCookie,自动使用 document.cookie
})
]
});import { createCsrfMiddleware } from "@aptx/api-plugin-csrf";
const client = new RequestClient();
client.use(createCsrfMiddleware({
cookieName: "XSRF-TOKEN",
headerName: "X-XSRF-TOKEN",
sameOriginOnly: true,
}));import { createCsrfMiddleware } from "@aptx/api-plugin-csrf";
import { cookies } from 'next/headers';
const csrf = createCsrfMiddleware({
cookieName: "XSRF-TOKEN",
headerName: "X-XSRF-TOKEN",
sameOriginOnly: true,
getCookie: (name) => {
const cookieStore = cookies();
return cookieStore.get(name)?.value; // SSR 必须提供 getCookie
}
});import { createCsrfMiddleware } from "@aptx/api-plugin-csrf";
const csrf = createCsrfMiddleware({
cookieName: "XSRF-TOKEN",
headerName: "X-XSRF-TOKEN",
sameOriginOnly: true,
getCookie: (name) => {
const cookies = req.cookies; // 从 cookie-parser 或 req.headers.cookie 读取
const value = cookies?.[name];
return value ? decodeURIComponent(value) : undefined;
}
});| 环境 | | | 默认 | 默认 |
|---|---|---|---|---|
| 浏览器 | ✓ 可用 | ✓ 可用 | ✓ 使用 document.cookie | ✓ 检查 origin |
| SSR (Next.js) | ✗ undefined | ✗ undefined | ✗ 需要自定义 getCookie | ✓ 返回 true(始终同源) |
| Node.js | ✗ undefined | ✗ undefined | ✗ 需要自定义 getCookie | ✓ 返回 true(始终同源) |
getCookiedocument is not definedgetCookiedecodeURIComponentsameOriginOnly: true| 文档 | 内容 |
|---|---|
| API Details | 完整 API 文档、配置选项详解、默认实现 |
| Environment Adaptation | 浏览器/SSR/Node 环境详细适配指南 |
| Testing Guide | 测试策略、测试示例代码 |
| Troubleshooting | 常见问题、故障排查、调试技巧 |