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

如何在AWS CDK配置中添加CSP响应头?

给CloudFront添加CSP响应头的AWS CDK实现方案

你当前使用的默认SECURITY_HEADERS响应头策略不包含CSP规则,需要创建自定义响应头策略来添加,以下是基于你现有代码的修改方案:

方案1:保留默认安全头+添加自定义CSP

这种方式会保留AWS默认安全头的同时,加入你自定义的CSP规则:

  1. 创建自定义响应头策略
    在创建CloudFront分发的代码前,添加以下代码:
// 创建包含CSP的自定义安全头策略
const customSecurityHeadersPolicy = new cloudfront.ResponseHeadersPolicy(this, `CustomSecurityPolicy-${context.environment}`, {
  responseHeadersPolicyName: `${context.appName}-security-headers-${context.environment}`,
  securityHeadersBehavior: {
    // 配置CSP规则,替换成你实际需要的内容
    contentSecurityPolicy: {
      contentSecurityPolicy: "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';",
      override: true,
    },
    // 以下是默认SECURITY_HEADERS包含的其他安全头,保持和默认一致
    contentTypeOptions: { override: true },
    frameOptions: { frameOption: cloudfront.FrameOption.DENY, override: true },
    referrerPolicy: { referrerPolicy: cloudfront.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN, override: true },
    strictTransportSecurity: { accessControlMaxAge: cdk.Duration.days(365), includeSubdomains: true, override: true },
    xssProtection: { protection: true, modeBlock: true, override: true },
  },
});
  1. 关联自定义策略到CloudFront分发
    替换你原来的addPropertyOverride代码为:
const cfnDistribution = cfDist.node.defaultChild as cloudfront.CfnDistribution;
cfnDistribution.addPropertyOverride(
  'DistributionConfig.DefaultCacheBehavior.ResponseHeadersPolicyId',
  customSecurityHeadersPolicy.responseHeadersPolicyId
);

方案2:仅添加CSP响应头

如果只需要CSP头,不需要其他默认安全头,可以用自定义头的方式:

  1. 创建仅含CSP的响应头策略
const cspResponsePolicy = new cloudfront.ResponseHeadersPolicy(this, `CspPolicy-${context.environment}`, {
  responseHeadersPolicyName: `${context.appName}-csp-headers-${context.environment}`,
  customHeadersBehavior: {
    customHeaders: [
      {
        header: 'Content-Security-Policy',
        value: "default-src 'self'; script-src 'self' https://your-cdn-domain.com; style-src 'self' 'unsafe-inline';", // 自定义CSP规则
        override: true,
      },
    ],
  },
});
  1. 关联策略到分发
    同样替换原来的addPropertyOverride代码,使用cspResponsePolicy.responseHeadersPolicyId即可。

注意事项

  • 务必根据你的前端应用实际需求调整CSP规则,比如允许加载的第三方脚本、图片域名等,避免出现资源加载失败的问题。
  • 如果使用的是AWS CDK v2,确保已经导入了@aws-cdk/aws-cloudfront相关模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:40:28