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

配置Content-Security-Policy报错,求A+级安全头修复方案

修复Content-Security-Policy配置错误方案

错误原因分析

1. gtag is not defined 错误

  • 当前script-src仅配置了www.googletagmanager,但谷歌分析脚本实际来自完整域名www.googletagmanager.com,域名格式不匹配
  • 执行gtag()函数需要允许对应内联脚本(或通过nonce/hash验证),当前配置未覆盖该规则
  • 缺少谷歌分析相关的脚本源(如www.google-analytics.com)

2. 字体加载被拒错误

  • 报错显示生效的font-src规则为data:* https://*,与你提供的配置不符,可能存在配置未正确生效的问题
  • Angular Material会使用data: URI格式的内嵌字体,当前配置未包含data:源,导致加载被拦截

修复后的CSP配置

以下配置适配谷歌分析、谷歌字体、Angular Material的需求,同时兼顾安全性:

Content-Security-Policy: 
  default-src 'self';
  style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.syncfusion.com;
  script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com;
  font-src 'self' data: https://fonts.gstatic.com https://fonts.googleapis.com https://cdn.syncfusion.com;
  img-src 'self' data: https://www.google-analytics.com;
  connect-src 'self' https://www.google-analytics.com;

配置说明

  • script-src:补充完整的谷歌Tag Manager、谷歌分析域名,临时保留'unsafe-inline'适配gtag()函数调用(后续可替换为nonce/hash提升安全性)
  • font-src:新增data:源,允许Angular Material的内嵌字体加载
  • img-src:添加谷歌分析统计像素所需的图片源
  • connect-src:允许谷歌分析的API请求

进阶优化(实现A+评分)

为移除'unsafe-inline'并获得最高安全评分,可采用nonce验证方案:

  1. 服务器端生成每个请求唯一的随机nonce值,同时注入到HTML的<meta>标签和CSP头中
  2. 给所有内联脚本/样式添加nonce="随机值"属性
  3. 修改CSP配置:
Content-Security-Policy: 
  default-src 'self';
  style-src 'self' 'nonce-你的随机值' https://fonts.googleapis.com https://cdn.syncfusion.com;
  script-src 'self' 'nonce-你的随机值' https://www.googletagmanager.com https://www.google-analytics.com;
  font-src 'self' data: https://fonts.gstatic.com https://fonts.googleapis.com https://cdn.syncfusion.com;
  img-src 'self' data: https://www.google-analytics.com;
  connect-src 'self' https://www.google-analytics.com;

验证建议

  • 用浏览器开发者工具的「控制台」「网络」面板确认无CSP违规报错
  • 通过安全头检测工具验证配置,确保符合A+级评分要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:16:01