透過 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

此 composable 提供 useFetch 的便利包裝。它會自動在標頭中新增 CSRF 令牌。

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

$csrfFetch

此 helper 提供 $fetch 的便利包裝。它會自動在標頭中新增 CSRF 令牌。

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

useCsrf

如果您需要存取 CSRF 令牌值,請使用此 composable。

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 令牌值會依照 OWASP 的 CSRF 速查表 中的說明儲存在 DOM 中。因此,必須為每個新的頁面請求產生 DOM,這在靜態網站(或預渲染路由)中並非如此。請參閱錯誤 #42

鳴謝