You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS App Router中CSP调试:如何定位违规script-src来源

问题描述

我正在使用Next.js应用(App Router)配置内容安全策略(CSP)安全标头,已经添加了script-src指令,但出现了内联脚本违反该指令的错误,Chrome浏览器无法指明具体是哪个脚本违规。如何不用通读整个代码库就能识别应用中所有的script-src来源?

配置片段(vercel.json)

{
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        {
          "key": "Content-Security-Policy",
          "value": "default-src 'self'; script-src 'self' *.posthog.com; style-src 'self';"
        }
      ]
    }
  ]
}

错误信息

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:"script-src 'self' https://*.posthog.com"。


解决方法

1. 启用CSP报告模式定位违规源

将CSP切换为仅报告模式,不会阻止脚本执行,但会完整记录所有违规行为的细节。修改vercel.json中的CSP配置:

{
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        {
          "key": "Content-Security-Policy-Report-Only",
          "value": "default-src 'self'; script-src 'self' *.posthog.com; style-src 'self'; report-uri /csp-report-endpoint;"
        }
      ]
    }
  ]
}
  • 打开Chrome开发者工具的Console和Security面板,就能看到包含内联脚本位置、哈希值的详细违规报告。
  • 若需服务器端收集报告,可在Next.js中创建/app/csp-report-endpoint/route.ts端点接收报告数据。

2. 用Chrome Security面板查看详情

打开Chrome DevTools并切换到Security标签页:

  • 点击Content Security Policy选项,查看当前生效的CSP规则。
  • 触发页面操作后,面板会列出所有违规资源的具体上下文,包括是React hydration脚本、第三方注入代码还是自定义内联脚本。

3. 临时添加辅助排查规则

如果报告模式信息不足,可临时在script-src中加入'unsafe-inline'和'report-sample',让浏览器输出违规脚本的片段:

"value": "default-src 'self'; script-src 'self' *.posthog.com 'unsafe-inline' 'report-sample'; style-src 'self';"

通过控制台输出的脚本片段快速定位来源,排查完成后立即移除'unsafe-inline'。

4. 处理Next.js自动注入的脚本

Next.js App Router会自动注入hydration、路由相关的内联脚本,这类脚本需要通过哈希值允许而非'unsafe-inline':

  • 启用报告模式后,从控制台的违规报告中提取对应脚本的SHA-256哈希值,添加到script-src中,示例:
"script-src 'self' *.posthog.com 'sha256-abcdef123456...';"

内容的提问来源于stack exchange,提问作者tbd_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:56:10