本文介绍了如何向 CloudFront 响应添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

解决方案

我建议使用 Lambda@Edge 将您要查找的任何标头附加到您的原始响应中,然后再返回给查看器.

当作为源响应事件添加时,它可以像下面的例子一样简单地完成.

 导入 jsondef lambda_handler(事件,上下文):响应=事件[记录"][0][cf"][响应"]标头 = 响应[标头"]headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age=63072000;包括子域;预加载'}];headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none';img-src '自我';脚本src'自我';style-src '自我';对象-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;模式=块'}];headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}];响应['标题'] = 标题返回响应

有关更多信息,请查看 使用 Lambda@Edge 和 Amazon CloudFront 添加 HTTP 安全标头 博客文章.

I test my website using https://observatory.mozilla.org/analyze and I got F score.

The reasons are:

Content Security Policy (CSP) header not implemented
X-XSS-Protection header not implemented
X-Frame-Options (XFO) header not implemented
...

I serve my website using CloudFront.

Where I put those missing headers to CloudFront?

解决方案

I would recommend using Lambda@Edge to append any headers that you're looking for to your origin response before it is returned to the viewer.

It can be done as simply as the below example when added as a Origin Response event.

 import json

 def lambda_handler(event, context):
     response = event["Records"][0]["cf"]["response"]
     headers = response["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'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}];
     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'}];

     response['headers'] = headers

     return response

For more information take a look at the Adding HTTP Security Headers Using Lambda@Edge and Amazon CloudFront blog post.

这篇关于如何向 CloudFront 响应添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:59