javascript - 在响应非 HTML 请求时设置内容安全策略是什么意思?

标签 javascript html ajax content-security-policy

我知道我可能会为我网站的主页设置一个 CSP header ,比如 https://example.com,以限制我可以加载脚本和其他资源的位置。但是,如果主页上没有 CSP,浏览器将如何处理后续请求的策略?

这是两个合二为一的例子:

  1. 我浏览到 https://example.com 并返回一些 HTML(无 CSP header )
  2. HTML 包含来自 https://example.com/script.js [*]
  3. 的脚本
  4. 此脚本通过向 https://api.example.com [*]
  5. 发出 GET 请求来自 API 的一些数据
  6. 然后相同的脚本打开到相同域的 websocket,https://api.example.com
  7. 然后同一脚本发出另一个请求,从外部发布到 https://api.analytics.com

[*] 在第 2 步和第 3 步中,如果 script.js 或 JSON 响应返回一个 restrictve CSP,如 Content-Security-Policy: default-src 'none'?是否会更改任何下游请求?浏览器是否采取任何措施来阻止脚本的任何请求?还是因为原始页面加载不包含任何 CSP 而被允许?

谢谢!

最佳答案

current CSP spec (版本 2)说(强调我的):

3.6. Policy applicability

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 无效。

因此,无论是否使用 Content-Security-Policy,您的脚本的行为都是相同的标题。

关于javascript - 在响应非 HTML 请求时设置内容安全策略是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819249/

相关文章:

javascript - DeviceMotionEvent 目前在哪里实现?

javascript - 使用 = 和 : in javascript 有什么区别

javascript - 获取 CouchDB 附件并将其显示在 html 页面上

javascript - 通过 Html.BeginForm 提交激活加载动画

javascript - backbone.js 集合 - 重复调用 fetch 以从服务器获取所有 "pages"

javascript - 如何在ajax post请求laravel中传递 token ?

javascript - 禁用 dojo dgrid 中的特定行

javascript - 将实体图深入到 2 系列条形图

javascript - Chrome 扩展程序 - 单击扩展程序、新选项卡和重定向

javascript - 使用 html 按钮调用加载特定图像的 Javascript 函数