Configuring X-Frame-Options Response Header on AWS CloudFront and S3
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.
Related videos on Youtube
wael
Updated on September 18, 2022Comments
-
wael over 1 year
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? -
wael over 8 yearsThanks for your response Mo Binni,but what i need is to set it in the server side so when the page loads the browser should not be allowed to render it in a frame or iframe
-
wael over 8 yearsSomething related to this forums.aws.amazon.com/thread.jspa?messageID=660139򡊫
-
Mo Binni over 8 yearsOooh what kind of server are you running?
-
wael over 8 yearsit's Cloudfront serving from an s3
-
Mo Binni over 8 yearsOh okay sorry, thought it was an angular specific question - fail
-
ConscriptMR almost 4 yearsHey, what trigger would you choose on the cloudfront event end?
-
ConscriptMR almost 4 yearsalso is it possible to do using python?
-
Sunny Tambi over 2 yearsNow it can be done on GUI using Response Header Policies. Check this out -- aws.amazon.com/blogs/networking-and-content-delivery/…