javascript - 为什么浏览器执行内容类型为 json 的 <script> ?

标签 javascript json security content-type

一些网络服务器在 JSON 响应前加上 while(1); ,e。 G。 while(1);['id',123]

这是为了防止 JSON hijacking :

This is to ensure some other site can't do nasty tricks to try to steal your data. For example, by replacing the array constructor, then including this JSON URL via a tag, a malicious third-party site could steal the data from the JSON response. By putting a while(1); at the start, the script will hang instead. @bdonlan, https://stackoverflow.com/a/871508/1647737

但是,这种对 JSON 内容的“误用”为 <script>源仅可能是因为网络浏览器(例如 Firefox)执行内容类型为 application/json 的脚本。 :

<!-- Content-type: application/json; charset=ISO-8859-1 -->
<script src="http://code.jsontest.com/?mine=1"></script>

浏览器不能简单地忽略内容类型不匹配的远程脚本吗?例如在上面的示例中,script type将是application/javascript (默认情况下),但响应的内容类型为 application/json 。为什么它仍然作为 JavaScript 执行?

最佳答案

浏览器往往对内容类型非常宽容。当 JavaScript 首次出现时,还没有标准化的 content-type

这样做的结果是,许多旧的 Web 服务器发送具有各种内容类型的 JavaScript,而浏览器几乎接受任何内容。如果浏览器请求 JavaScript,它会假设它已返回 JavaScript 并执行它。

(甚至可以将 JavaScript 隐藏在 GIF 中并让它执行。一旦引用: http://iamajin.blogspot.com/2014/11/when-gifs-serve-javascript.html )

由于 Web 基础设施的首要规则是“不要破坏 Web”,因此没有人愿意更改脚本的安全模型,因此必须采取其他解决方法.

换句话说,有人将常规 JSON 作为 JSONP 提供服务,如果浏览器拒绝执行它,那么全世界都会认为浏览器已损坏,而不是 Web 服务器。

(感谢昆汀提供的引用链接并为我制定了时间表。)

关于javascript - 为什么浏览器执行内容类型为 json 的 &lt;script&gt; ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863357/

相关文章:

javascript - 2020 年后 Javascript 月份错误

ios - 如何使用flutter,wordpress在我的应用程序中添加拉动刷新?

security - IP 地址和端口是否应该被视为 secret ?

security - SQL 注入(inject)或 Server.HTMLEncode 或两者兼而有之?经典 ASP

正确的 kill syscall linux 使用模式

javascript - iframe 中的视口(viewport)元标记

javascript - 滚动条问题

javascript - MissingSchemaError : Schema hasn't been registered for model "User"

JavaScript 将键/值列表与天匹配

php - 带有 json 响应的 jQuery ajax 表单