透過 100+ 個秘訣學習 Nuxt!

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

鳴謝