问题描述
我了解我可能会为网站主页设置CSP标头,例如 https://example.com
,以限制可以从何处加载脚本和其他资源。但是,如果主页上没有 CSP ,浏览器将如何处理后续请求的策略?
I understand that I might set a CSP header for the main page of my site, say https://example.com
, to restrict from where I can load scripts and other resources. But, if there is no CSP on the main page, how will the browser treat a policy on a subsequent request?
这是两个示例在其中一个:
This is two examples in one:
- 我浏览到
https://example.com
并获取返回一些HTML(没有CSP标头) - HTML包含来自
https://example.com/script.js
的脚本*] - 此脚本通过向
https://api.example.com
发出GET,从API请求一些数据] - 然后,相同的脚本将Websocket打开到相同的域,即
https://api.example.com
- 然后同一脚本发出另一个请求,在外部发布到
https://api.analytics.com
- I browse to
https://example.com
and get back some HTML (no CSP header) - The HTML includes a script from
https://example.com/script.js
[*] - This script requests some data from the API by issuing a GET to
https://api.example.com
[*] - The same script then opens a websocket to the same domain,
https://api.example.com
- The same script then makes another request, POSTing externally to
https://api.analytics.com
[*]在步骤2和3中,如果script.js或JSON响应返回带有受限CSP的内容,例如 Content-安全策略:default-src'none'
?下游的要求会改变吗?浏览器是否采取任何措施来阻止脚本的任何请求?还是因为原始页面加载不包含任何CSP而被允许?
[*] In steps 2 and 3, what would happen if the script.js or the JSON response came back with a restrictve CSP, like Content-Security-Policy: default-src 'none'
? Would any downstream requests be changed? Does the browser do anything to prevent any of the script's requests? Or are the allowed because the original page load did not include any CSP?
谢谢!
推荐答案
(版本2)说(强调我的意思):
The current CSP spec (version 2) says (emphasis mine):
策略与受保护的资源相关联,并针对该资源实施或监视。 如果资源没有创建新的执行上下文(例如,当在文档中包含脚本,图像或样式表时),然后,随该资源提供的所有策略都将被丢弃而无效。它的执行受包含上下文的一个或多个策略约束。
Policies are associated with an protected resource, and enforced or monitored for that resource. If a resource does not create a new execution context (for example, when including a script, image, or stylesheet into a document), then any policies delivered with that resource are discarded without effect. Its execution is subject to the policy or policies of the including context.
CSP仅适用于创建新执行上下文的资源(即网页) ),其中仅包含顶级文档,嵌入的对象(如< iframe>
s)和作为Web Workers加载的脚本。如果资源是通过HTTP提供的,并且未以创建新执行上下文的方式使用资源,则CSP无效。
CSPs only apply to resources that create a new execution context (i.e., a Web page), which includes only top-level documents, embedded objects like <iframe>
s, and scripts loaded as Web Workers. If a resource is served over HTTP and that reource is not used in a way that creates a new execution context, the CSP has no effect.
因此,无论脚本是否执行,其脚本的行为都相同。它们带有 Content-Security-Policy
标头。
Therefore, your scripts will behave identically whether or not they are served with a Content-Security-Policy
header.
这篇关于在响应非HTML请求时设置内容安全策略是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!