【问题标题】:Content Security Policy in Nuxt.jsNuxt.js 中的内容安全策略
【发布时间】:2020-05-19 13:15:12
【问题描述】:

是否有人成功将 CSP 添加到 Nuxt 应用?

我尝试了Helmet,但它似乎与 nuxt.config.js 文件不兼容。

还尝试在 Nuxt 中的 Render property 上添加 csp,但在某些脚本需要 nonce 时遇到问题。

这是我的 nuxt.config.js 中 Render 属性的要点,这对吗?

您如何在 Nuxt 中生成随机数?

render: {
  csp: {
    hashAlgorithm: 'sha256',
    policies: {
      'script-src': [
        'self',
        'unsafe-inline',
        'http://assets.adobedtm.com',
        'https://cdn.polyfill.io/',
        'https://www.everestjs.net',
        'https://www.google-analytics.com',
        'http://localhost:8001',
        "'sha256-<hash>'"
      ],
    },
    reportOnly: false,
    addMeta: true
  }
},

【问题讨论】:

  • 您能分享一下您是如何解决这个问题的吗?

标签: vue.js nuxt.js content-security-policy nonce


【解决方案1】:

首先确保在您的nuxt.config.js 中设置了以下内容:

render: { csp: true }

这是一个实现这一目标的模块。请注意,它目前尚未经过充分测试。

import { randomBytes } from 'crypto'

export default function cspModule() {
  // Set nuxt CSP options.
  this.options.render.csp = {
    reportOnly: true,
    hashAlgorithm: 'sha256',
  }

  this.nuxt.hook('render:routeContext', (nuxtContext) => {
    // Generate a 128 bit random nonce every request.
    const nonce = randomBytes(16).toString('base64')
    // Inject nonce into vuex state before state is serialized into window.__NUXT__.
    nuxtContext.state.nonce = nonce
  })

  this.nuxt.hook(
    'render:route',
    (url, { cspScriptSrcHashes }, { nuxt: nuxtContext }) => {
      // Extract nonce generated in render:routeContext.
      const nonce = nuxtContext.state.nonce
      // Add nonce to cspScriptSrcHashes. Nuxt will populate all entries in this array
      // to the csp header and meta tags as part of the script-src csp policy.
      cspScriptSrcHashes.push(`'nonce-${nonce}'`)
    }
  )
}

此方法的一个警告是,nonce 仅适用于 script-src csp 策略。但在大多数情况下,无论如何它只需要脚本。

Source


请记住,nonce(“数字只使用一次”)只对 SSR 有意义,因为它在每个请求中都必须是唯一的。对于 SSG(即nuxt generate)来说,实现这一点要困难得多(也许在 Web 服务器上使用转换?)。

more info

【讨论】:

    【解决方案2】:

    您可以使用nuxt-helmet 为您完成此操作。这是一个非常容易集成的软件包,只需在您的nuxt.config.js 中添加几行代码。

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2017-09-07
      • 2021-01-11
      • 2016-06-22
      • 2014-07-26
      相关资源
      最近更新 更多