Skip to content

CSRF 保护

¥CSRF Protection

此中间件通过检查 Origin 标头和 Sec-Fetch-Site 标头来防止 CSRF 攻击。如果任一验证通过,则允许该请求。

¥This middleware protects against CSRF attacks by checking both the Origin header and the Sec-Fetch-Site header. The request is allowed if either validation passes.

中间件仅验证以下请求:

¥The middleware only validates requests that:

  • 使用不安全的 HTTP 方法(例如 GET、HEAD 或 OPTIONS)

    ¥Use unsafe HTTP methods (not GET, HEAD, or OPTIONS)

  • 具有可通过 HTML 表单发送的内容类型(application/x-www-form-urlencodedmultipart/form-datatext/plain

    ¥Have content types that can be sent by HTML forms (application/x-www-form-urlencoded, multipart/form-data, or text/plain)

不发送 Origin 标头的旧浏览器,或使用反向代理删除这些标头的环境,可能无法正常工作。在这样的环境中,请使用其他 CSRF 令牌方法。

¥Old browsers that do not send Origin headers, or environments that use reverse proxies to remove these headers, may not work well. In such environments, use other CSRF token methods.

导入

¥Import

ts
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'

用法

¥Usage

ts
const app = new Hono()

// Default: both origin and sec-fetch-site validation
app.use(csrf())

// Allow specific origins
app.use(csrf({ origin: 'https://myapp.example.com' }))

// Allow multiple origins
app.use(
  csrf({
    origin: [
      'https://myapp.example.com',
      'https://development.myapp.example.com',
    ],
  })
)

// Allow specific sec-fetch-site values
app.use(csrf({ secFetchSite: 'same-origin' }))
app.use(csrf({ secFetchSite: ['same-origin', 'none'] }))

// Dynamic origin validation
// It is strongly recommended that the protocol be verified to ensure a match to `$`.
// You should *never* do a forward match.
app.use(
  '*',
  csrf({
    origin: (origin) =>
      /https:\/\/(\w+\.)?myapp\.example\.com$/.test(origin),
  })
)

// Dynamic sec-fetch-site validation
app.use(
  csrf({
    secFetchSite: (secFetchSite, c) => {
      // Always allow same-origin
      if (secFetchSite === 'same-origin') return true
      // Allow cross-site for webhook endpoints
      if (
        secFetchSite === 'cross-site' &&
        c.req.path.startsWith('/webhook/')
      ) {
        return true
      }
      return false
    },
  })
)

选项

¥Options

optional origin:string | string[] | Function

指定允许的来源,以进行 CSRF 保护。

¥Specify allowed origins for CSRF protection.

  • string:单个允许来源(例如,'https://example.com'

    ¥string: Single allowed origin (e.g., 'https://example.com')

  • string[]:允许来源数组

    ¥string[]: Array of allowed origins

  • Function:自定义处理程序 (origin: string, context: Context) => boolean,用于灵活的来源验证和旁路逻辑

    ¥Function: Custom handler (origin: string, context: Context) => boolean for flexible origin validation and bypass logic

默认值:仅与请求 URL 同源

¥Default: Only same origin as the request URL

函数处理程序接收请求的 Origin 标头值和请求上下文,从而允许基于请求属性(例如路径、标头或其他上下文数据)进行动态验证。

¥The function handler receives the request's Origin header value and the request context, allowing for dynamic validation based on request properties like path, headers, or other context data.

optional secFetchSite:string | string[] | Function

使用 获取元数据 指定允许的 Sec-Fetch-Site 标头值,以进行 CSRF 保护。

¥Specify allowed Sec-Fetch-Site header values for CSRF protection using Fetch Metadata.

  • string:单个允许值(例如,'same-origin'

    ¥string: Single allowed value (e.g., 'same-origin')

  • string[]:允许值数组(例如 ['same-origin', 'none']

    ¥string[]: Array of allowed values (e.g., ['same-origin', 'none'])

  • Function:自定义处理程序 (secFetchSite: string, context: Context) => boolean,用于灵活的验证

    ¥Function: Custom handler (secFetchSite: string, context: Context) => boolean for flexible validation

默认值:仅允许 'same-origin'

¥Default: Only allows 'same-origin'

标准 Sec-Fetch-Site 值:

¥Standard Sec-Fetch-Site values:

  • same-origin:来自相同来源的请求

    ¥same-origin: Request from same origin

  • same-site:来自同一站点(不同子域名)的请求

    ¥same-site: Request from same site (different subdomain)

  • cross-site:来自不同站点的请求

    ¥cross-site: Request from different site

  • none:非来自网页(例如,浏览器地址栏、书签)的请求

    ¥none: Request not from a web page (e.g., browser address bar, bookmark)

函数处理程序接收请求的 Sec-Fetch-Site 标头值和请求上下文,从而基于请求属性启用动态验证。

¥The function handler receives the request's Sec-Fetch-Site header value and the request context, enabling dynamic validation based on request properties.

Hono v4.10 中文网 - 粤ICP备13048890号