How to add headers to cloudfront response?

六月ゝ 毕业季﹏ 提交于 2021-01-28 12:17:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/63203619/how-to-add-headers-to-cloudfront-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!