2 minutes
Configuring CSP with AWS CloudFront
Content Security Policy and Amazon CloudFront
When I first started using CloudFront CDN I wasn’t sure how to properly update the CSP to allow resources from my approved origins. I tried various combinations of rulesets in the document meta tag but the resources were still being blocked. I found they were being overridden by the headers provided by CloudFront. I attempted to add custom headers using the AWS S3 custom metadata feature but it didn’t work as expected. It turns out there are a couple of ways to update the CSP header that CloudFront uses; Response header policies or Lambda@Edge; The former is much easier to implement in my opinion.
Configuring CSP headers with CloudFront Policies
You can pick the rules that CloudFront uses as values for the Content-Security-Policy header by creating a response headers policy. This can be done by using several different methods - CloudFront console, CLI, CloudFormation, or CloudFront API.
If using the console simply visit “CloudFront->Policies->Response headers” and hit “Create response headers policy” under the “Custom policies” section.

After adding your own rules you can then you can attach it to a cache behavior in a CloudFront distribution.
Configuring CSP headers with Lambda@Edge
Lambda@Edge can also be used to alter the origin response before it gets cached in CloudFront. This service provides the ability to execute a Lambda function at an Amazon CloudFront Edge Location. Basically you want to create a new Lambda@Edge function and associate it with your CloudFront distribution. This can be done by visiting the CloudFront console and navigating to the “Behaviors” tab of the chosen distribution. An example for a Node.js function will look something like this:
"use strict";
exports.handler = (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;
headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; "}];
callback(null, response);
};
AWS documentation:
- https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/modifying-response-headers.html
- https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/creating-response-headers-policies.html
- https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-how-it-works.html