【问题标题】:Nextjs preloaded scripts blocked with strict CSPNextjs 预加载脚本被严格的 CSP 阻止
【发布时间】:2021-06-11 19:41:44
【问题描述】:

我正在尝试基于next.js example 在我的下一个应用程序中设置strict CSP。在我的_document.js 中,我有以下内容:

const cspHashOf = (text) => {
  const hash = crypto.createHash('sha256')
  hash.update(text)
  return `'sha256-${hash.digest('base64')}'`
}

let cspStr = ''
for (let k in csp) {
  cspStr += `${k} ${csp[k]}; `
}

...

    render() {
    const nonce = crypto.randomBytes(8).toString('base64')

    let csp = {
      'object-src': "'none'",
      'base-uri': "'self'",
      'script-src': `'nonce-${nonce}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http: ${cspHashOf(
        NextScript.getInlineScriptSource(this.props)
      )}`,
    }

    let cspStr = ''
    for (let k in csp) {
      cspStr += `${k} ${csp[k]}; `
    }

    return (
      <Html>
        <Head>
          <meta httpEquiv="Content-Security-Policy" content={cspStr} />
          ...
        </Head>
        <body>
          ...
          <NextScript nonce={nonce} />
        </body>
      </Html>
    )

在呈现的页面中,我有所有这些来自 Next 的预加载块被阻止

<link rel="preload" href="/_next/static/chunks/8be9d4c0d98df170721d8fe575c2a4bcd5b2fbe4.e7c8a9ea6074f4dcaa51.js" as="script">
<link rel="preload" href="/_next/static/chunks/863050a7585a2b3888f2e4b96c75689f1ae4a93d.a73c594ed7ed04a682dc.js" as="script">
<link rel="preload" href="/_next/static/chunks/be8560b560b3990e61cbef828a20e51dc9370d83.4acbf8ef4e1b51b0bc0f.js" as="script">
<link rel="preload" href="/_next/static/chunks/be8560b560b3990e61cbef828a20e51dc9370d83_CSS.6164c81b6ed04bb13dbd.js" as="script">

如何防止它们被屏蔽?

【问题讨论】:

  • 只想指出,如果您在脚本中使用哈希,则不一定需要使用随机数。旧的 with-strict-csp Next.js 示例曾经使用 nonce,但改为 it's been updated it to use a hash
  • 感谢@juliomalves - 我在我所有的 3rds 方脚本中都使用了 nonce,因此更容易始终包含它

标签: next.js content-security-policy


【解决方案1】:

我最终能够通过将nonce 作为道具传递给Head 来解决这个问题

<Head nonce={nonce}>

Next.js 中的相关文档不存在!如果有人找到它来分享链接,我会很高兴

【讨论】:

  • 如果您希望允许预加载脚本,您只需在&lt;link rel="preload" href="some_script.js" as="script" nonce="{nonce}"&gt; 标签中添加'nonce-value'。您的意思是 NextJS 会自动将 nonce="{nonce}" 属性从 &lt;head nonce="{nonce}"&gt; 部分重新分配到嵌套的 &lt;link&gt; 标签?
  • 是的。如果没有将 nonce 传递给 nextjs 组件,它生成的预加载标签没有 nonce
猜你喜欢
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 2021-05-30
  • 2022-01-04
  • 2015-07-25
相关资源
最近更新 更多