Configuring a Content-Security-Policy with Lambda Edge

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks.
Configuring Content Security Policy involves adding the Content-Security-Policy HTTP header to a web page and giving it values to control what resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack.

Step 1. Create Lambda Function

Step 2. Add basic Content-Security-Policy

"use strict";
exports.handler = (event, context, callback) => {
//Get contents of response
const response = event.Records[0].cf.response;
const headers = response.headers;

//Set new headers
headers["strict-transport-security"] = [
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubdomains; preload",
headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none’; " +
"font-src ; " +
"form-action 'self'; " +
"frame-src ; " +
"media-src ; " +
"frame-ancestors 'self'; " +
"base-uri 'self'; " +
"manifest-src 'self'; " +
"img-src 'self'; " +
"style-src 'self' 'unsafe-inline'; " +
"script-src 'self'; " +
"connect-src ;"
headers["x-content-type-options"] = [{ key: "X-Content-Type-Options", value: "nosniff" },];
headers["x-frame-options"] = [{ key: "X-Frame-Options", value: "DENY" }];
headers["x-xss-protection"] = [{ key: "X-XSS-Protection", value: "1; mode=block" },];
headers["referrer-policy"] = [{ key: "Referrer-Policy", value: "same-origin" },];

//Return modified response
callback(null, response);

Step 3. Configure CloudFront Distribution to use Lambda



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store