csurf
nuxt-csurf

用於 Nuxt 的跨站請求偽造 (CSRF) 防護

nuxt-oa-social-card

npm versionnpm downloadsLicenseNuxt

Nuxt Csurf

跨站請求偽造 (CSRF) 防護。
為 CSRF 令牌的建立和驗證建立中介軟體。

✅ 支援 Node.js 伺服器和無伺服器環境
✅ 支援通用和客戶端渲染 (ssr: true|false)
✅ 路由級配置
✅ TypeScript
❌ 由於某些限制,不支援靜態託管和 nitro 預渲染 *

安裝

npx nuxi@latest module add csurf

全域性配置

// nuxt.config.js
export default defineNuxtConfig({
  modules: ['nuxt-csurf'],
  csurf: { // optional
    https: false, // default true if in production
    cookieKey: '', // "__Host-csrf" if https is true otherwise just "csrf"
    cookie: { // CookieSerializeOptions from unjs/cookie-es
      path: '/',
      httpOnly: true,
      sameSite: 'strict'
    },
    methodsToProtect: ['POST', 'PUT', 'PATCH'], // the request methods we want CSRF protection for
    encryptSecret: /** a 32 bits secret */, // for stateless server (like serverless runtime), random bytes by default
    encryptAlgorithm: 'aes-256-cbc', // by default 'aes-256-cbc' (node), 'AES-CBC' (serverless)
    addCsrfTokenToEventCtx: true, // default false, to run useCsrfFetch on server set it to true
    headerName: 'csrf-token' // the header where the csrf token is stored
  } 
})

按路由配置

要啟用按路由配置,請使用如下所示的 routeRules

export default defineNuxtConfig({
  routeRules: {
    '/api/nocsrf': {
      csurf: false
    },
    '/api/test': {
      csurf: {
        methodsToProtect: ['POST'] // protect POST request only
      }
    }
  }
})

useCsrfFetch

此可組合項提供了一個便捷的 useFetch 包裝器。它會自動在請求頭中新增 CSRF 令牌。

const { data, pending, error, refresh } = useCsrfFetch('/api/login', { query: param1: 'value1' })

$csrfFetch

此輔助函式提供了一個便捷的 $fetch 包裝器。它會自動在請求頭中新增 CSRF 令牌。

const { $csrfFetch } = useNuxtApp()
const { data } = await $csrfFetch('/api/login', { method: 'POST', body:, headers:})

useCsrf

如果您需要訪問 CSRF 令牌值,請使用此可組合項。

const { csrf } = useCsrf()
console.log(csrf) // something like: mo4+MrFaeXP7fhAie0o2qw==:tLUaqtHW6evx/coGQVAhtGAR+v6cxgFtrqmkOsuAMag8PHRnMwpbGGUO0TPJjL+4

在 localhost 上嘗試生產環境 (yarn preview)

NITRO_CSURF_HTTPS=false
NITRO_CSURF_COOKIE_KEY=csrf

限制

CSRF 令牌值儲存在 DOM 中,如 Owasp 的 CSRF 備忘錄 中所述。因此,對於每個新的頁面請求,都必須生成 DOM,而這對於靜態站點(或預渲染路由)來說是不適用的。參見錯誤 #42

鳴謝