如何在AWS CDK中为CloudFrontWebDistribution启用SecurityHeaders托管响应头策略?
Hey there! I get it—working with the older CloudFrontWebDistribution construct can feel a bit tricky when most docs focus on the newer Distribution resource. But you absolutely can enable the SecurityHeaders managed response headers policy by leveraging a lesser-known property in your distribution's behavior configurations.
Here's how to do it:
Use the pre-defined SecurityHeaders managed policy ID
AWS provides a fixed, universal ID for the SecurityHeaders managed response headers policy:67f7725c-6f97-4210-82d7-5512b31e9d03. You can reference this ID directly without creating a custom policy first.Add the policy ID to your CloudFront behavior
Even though it's not prominently documented, the behavior configuration forCloudFrontWebDistributionsupports theresponseHeadersPolicyIdproperty. Add this to your default (or target) behavior to attach the managed policy.
Modified Code Example
Here's your updated TypeScript code with the SecurityHeaders policy enabled:
const cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, 'distribution', { originConfigs: [ { s3OriginSource: { s3BucketSource: webBucket, originAccessIdentity: originAccessIdentity, }, behaviors: [ { isDefaultBehavior: true, defaultTtl: Duration.seconds(1), lambdaFunctionAssociations: [ { eventType: LambdaEdgeEventType.VIEWER_REQUEST, lambdaFunction: midwayEdgeFunction.currentVersion, }, ], // Add this line to enable SecurityHeaders managed policy responseHeadersPolicyId: '67f7725c-6f97-4210-82d7-5512b31e9d03', }, ], }, ], defaultRootObject: 'index.html', viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(props.certificate, { aliases: [props.stageProps.cloud_front_domain_name], sslMethod: cloudfront.SSLMethod.SNI, securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2019, }), viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY, loggingConfig: { bucket: logBucket, includeCookies: true, prefix: 'cflogs/', }, });
Quick Notes:
- If you need other managed response headers policies (like CORSWithPreflight or CustomSecurityHeaders), you can find their respective fixed IDs in AWS CloudFront's official documentation.
- This works because the
responseHeadersPolicyIdproperty maps directly to the underlying CloudFront API parameter, which supports both custom and managed policy IDs seamlessly.
内容的提问来源于stack exchange,提问作者bappak

