下一个.js
这是Edge-CSRF的"Next.js"集成的文件. 与Next.js 13、14和15的融合工作.
快速启动
首先,将整合库添加为您的应用程序的依赖性 :
npm install @edge-csrf/nextjs
# or
pnpm add @edge-csrf/nextjs
# or
yarn add @edge-csrf/nextjs
下一个,创建中间软件文件(middleware.ts)用于您的项目并添加边缘-CSRF中间软件:
// middleware.ts
import { createCsrfMiddleware } from '@edge-csrf/nextjs';
// initalize csrf protection middleware
const csrfMiddleware = createCsrfMiddleware({
cookie: {
secure: process.env.NODE_ENV === 'production',
},
});
export const middleware = csrfMiddleware;
现在,所有HTTP提交请求(如POST,PUT,DELETE,PATCH)如果不包括一个有效的CSRF令牌,将被拒绝. 在表格中添加CSRF符号,您可以从表格中获取 X-CSRF-Token HTTP 响应头服务器侧或客户端侧. 例如:
应用路由器
// app/page.tsx
import { headers } from 'next/headers';
export default async function Page() {
const h = await headers();
const csrfToken = h.get('X-CSRF-Token') || 'missing';
return (
<form action="/api/form-handler" method="post">
<input type="hidden" value={csrfToken}>
<input type="text" name="my-input">
<input type="submit">
</form>
);
}
// app/form-handler/route.ts
import { NextResponse } from 'next/server';
export async function POST() {
return NextResponse.json({ status: 'success' });
}
页面路由器
// pages/form.ts
import type { NextPage, GetServerSideProps } from 'next';
import React from 'react';
type Props = {
csrfToken: string;
};
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
const csrfToken = res.getHeader('x-csrf-token') || 'missing';
return { props: { csrfToken } };
}
const FormPage: NextPage<Props> = ({ csrfToken }) => {
return (
<form action="/api/form-handler" method="post">
<input type="hidden" value={csrfToken}>
<input type="text" name="my-input">
<input type="submit">
</form>
);
}
export default FormPage;
// pages/api/form-handler.ts
import type { NextApiRequest, NextApiResponse } from 'next';
type Data = {
status: string
};
export default function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
// this code won't execute unless CSRF token passes validation
res.status(200).json({ status: 'success' });
}
实例
这里有些 实例 在本寄存器中:
| 版本 | 路由器 | 执行情况 |
|---|---|---|
| 下册.js 13 | 应用程序路由器 | HTML 窗体 |
| 下册.js 13 | 应用程序路由器 | JavaScript (动力学) |
| 下册.js 13 | 应用程序路由器 | Java 脚本( 静态) |
| 下册.js 13 | 页面路由器 | HTML 窗体 |
| 下一个.js 14 | 应用程序路由器 | HTML 窗体 |
| 下一个.js 14 | 应用程序路由器 | JavaScript (动力学) |
| 下一个.js 14 | 应用程序路由器 | Java 脚本( 静态) |
| 下一个.js 14 | 应用程序路由器 | 哨兵 |
| 下一个.js 14 | 应用程序路由器 | 服务器动作( 窗体) |
| 下一个.js 14 | 应用程序路由器 | 服务器动作( 非窗体) |
| 下一个.js 14 | 页面路由器 | HTML 窗体 |
| 下一个.js 15 | 应用程序路由器 | HTML 窗体 |
| 下一个.js 15 | 应用程序路由器 | JavaScript (动力学) |
| 下一个.js 15 | 应用程序路由器 | Java 脚本( 静态) |
| 下一个.js 15 | 应用程序路由器 | 哨兵 |
| 下一个.js 15 | 应用程序路由器 | 服务器动作( 窗体) |
| 下一个.js 15 | 应用程序路由器 | 服务器动作( 非窗体) |
| 下一个.js 15 | 页面路由器 | HTML 窗体 |
低级执行
如果您想要对响应进行较低级别的控制, 或者CSRF 保护会应用到哪个路线, 您可以使用 createCsrfProtect() 创建功能的方法,您可以在自定义的中间软件内使用:
// middleware.ts
import { CsrfError, createCsrfProtect } from '@edge-csrf/nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// initalize csrf protection method
const csrfProtect = createCsrfProtect({
cookie: {
secure: process.env.NODE_ENV === 'production',
},
});
// Next.js middleware function
export const middleware = async (request: NextRequest) => {
const response = NextResponse.next();
try {
await csrfProtect(request, response);
} catch (err) {
if (err instanceof CsrfError) return new NextResponse('invalid csrf token', { status: 403 });
throw err;
}
return response;
};
配置
// default config
{
cookie: {
name: '_csrfSecret',
path: '/',
maxAge: undefined,
domain: '',
secure: true,
httpOnly: true,
sameSite: 'strict'
},
excludePathPrefixes: ['/_next/'],
ignoreMethods: ['GET', 'HEAD', 'OPTIONS'],
saltByteLength: 8,
secretByteLength: 18,
token: {
fieldName: 'csrf_token',
responseHeader: 'X-CSRF-Token',
value: undefined
}
}
API 密码
下列出口品列于 @edge-csrf/nextjs 模块 :
类型
NextCsrfProtect - A function that implements CSRF protection for Next.js requests
* @param {NextRequest} request - The Next.js request instance
* @param {NextResponse} response - The Next.js response instance
* @returns {Promise<void>} - The function completed successfully
* @throws {CsrfError} - The function encountered a CSRF error
类
CsrfError - A class that inherits from Error and represents CSRF errors
方法
createCsrfMiddleware([, options]) - Create a new instance of Next.js middleware
* @param {object} options - The configuration options
* @returns {Middleware} - The middleware
createCsrfProtect([, options]) - Create a lower-level function that can be used inside Next.js middleware
to implement CSRF protection for requests
* @param {object} options - The configuration options
* @returns {NextCsrfProtect} - The CSRF protection function