I'd like to add X-Frame-Options
HTTP response header for static content hosted on Amazon S3 with a Cloudfront cache. How can I add these headers?
You can add the x-frame-options header to the response from CloudFront / S3 using a Lambda@Edge function. The lambda code runs within the local edge locations, but needs to be created and maintained in the us-east-1
region.
The example code here uses nodeJS 6.10 to add the response header
'use strict';
exports.handler = (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;
response.headers['x-frame-options'] = [{"key":"X-Frame-Options","value":"SAMEORIGIN"}];
console.log(response.headers);
callback(null, response);
};
Create a definitive version of the Lambda, then set the Lambda Version's trigger configuration as the CloudFront origin-response
Event type for your path pattern behavior.
The example code logs events to CloudWatch logs service for debugging purposes. If you don't already have one you will need to setup a lambda execution IAM role that allows a policy allowing CloudWatch logs actions to be assumed by edgelambda.amazonaws.com
and lambda.amazonaws.com
.
Basic Lambda Execution Policy allowing logs to be written to CloudWatch:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
Trust Relationship allowing Lambda and Lambda@Edge to assume the role :
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"edgelambda.amazonaws.com",
"lambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
It would be better if AWS simply allowed the x-frame-options header to be set in the GUI but until then this solution works and will allow you to keep your Security Auditors happy.