5

I would like to add x-frame-options as sameorigin to AWS CloudFront service that serving my application on S3 bucket.

I don't want add new Lambda function to edit requests header.

Actually I found a place under like Attached file:

CloudFront Distributions -> My Distribution settings -> Origins and Origin Groups -> S3 Content item that represent my app -> add Origin Custom Headers -> Header name: x-frame-options, Value :sameorigin

but when deployment going to finish still getting old headers in all related request on S3 bucket files and URL's.

enter image description here

How can I add to headers without any Lambda function just directly working with existing AWS CloudFront panel?

4

3 回答 3

10

您正在配置的“源自定义标头”不是添加到源响应的标头,而是添加到对源的请求的标头。从CloudFront 文档

您可以配置 CloudFront 以将自定义标头添加到它发送到您的源的请求中。这些自定义标头使您能够从您的来源发送和收集典型查看器请求无法获得的信息。这些标题甚至可以为每个来源定制。CloudFront 支持自定义和 Amazon S3 源的自定义标头。

所以这不是添加响应头的选项。虽然存在使用 S3 元数据来影响返回给查看器的标头的可能性,但这仅适用于Content-Type-header,因此这不是一个选项。

最好的选择是使用 Lambda@Edge 函数。虽然这听起来像是一个麻烦且昂贵的解决方案,但实际上并非如此。对于您的用例,该 Lambda@Edge 函数的代码可以很简单,如下所示:

def lambda_handler(event, context):
    response = event["Records"][0]["cf"]["response"]
    response["headers"]["x-frame-options"] = ":sameorigin"
    return response

当您将此 Lambda@Edge 函数配置为触发 CloudFront 中的“原始响应”事件时,它不会针对每个查看器请求执行,而是仅当返回到查看器的内容未被 CloudFront 缓存且必须首先从 S3 获取。这有助于最大限度地减少由执行 Lambda@Edge 函数引起的额外延迟和成本。

于 2020-04-08T19:20:21.587 回答
8

这个 SO 答案帮助了我,但我首先找到了这个问题,所以也在这里分享答案。

您现在可以通过CloudFront 函数设置标头,而不必创建 Lambda@Edge 函数。文档中提供的示例代码非常适合设置过时浏览器安全性所需的标头:

function handler(event) {
    var response = event.response;
    var headers = response.headers;

    // Set HTTP security headers
    // Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation 
    headers['strict-transport-security'] = { value: 'max-age=63072000; includeSubdomains; preload'}; 
    headers['content-security-policy'] = { value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}; 
    headers['x-content-type-options'] = { value: 'nosniff'}; 
    headers['x-frame-options'] = {value: 'DENY'}; 
    headers['x-xss-protection'] = {value: '1; mode=block'}; 

    // Return the response to viewers 
    return response;
}
于 2021-07-29T17:51:19.730 回答
3

自 2021 年 11 月起,Cloudfront 现在支持Response Headers Policies。这允许您将策略与您的分配相关联,该分配定义要返回的其他响应标头。如果您不想使用完整的安全标头预设策略,则可以使用x-frame-options.

于 2022-01-18T23:02:59.087 回答