Tornado - JSON 作为响应发送的输出将被包装在字典中

Tornado - JSON Output sent as Response to be wrapped in dictionary

我在文档中看到了这一部分:

RequestHandler.write(chunk)

Writes the given chunk to the output buffer.

To write the output to the network, use the flush() method below.

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009

所以我有几个与此相关的问题:

  1. 这是什么意思?

If the given chunk is a dictionary, we write it as JSON.

  1. 这是什么意思?

Note that lists are not converted to JSON because of a potential cross-site security vulnerability.

  1. 这是什么意思?在这里,JSON 输出是什么意思?为什么要用字典包装它?

All JSON output should be wrapped in a dictionary.

  1. 这有两个子部分:

    一个。从 Tornadoclient 发送 JSON responses 的最佳方式是什么?

    b。发送回复的更好方法是什么?如果不是JSON,那是什么?如果它 JSON,那么只需提及子部分 (a) 的答案。

请尽量按编号方式回答所有部分及其子部分,以便我能正确理解。

  1. What does it mean by this?

    If the given chunk is a dictionary, we write it as JSON.

这意味着,如果你将 dict 传递给 write,我们将被 automatically json 编码。方法write可以处理dictbyteunicode_type(简化为str)。

  1. What does it mean by this?

    Note that lists are not converted to JSON because of a potential cross-site security vulnerability.

假设您提供了一些服务并且有请求 /example/my_service/user_data.json 和 JSON 响应。

如果顶级对象是一个数组,如:

["John Smith", "email@mail"]

然后攻击者可以重新定义 Array 的构造函数,然后添加带有 /example/my_service/user_data.json 的脚本标记,该标记会立即被评估 - 数组是使用攻击者的构造函数创建的。这是因为独立数组是有效的javascript代码。

因为除了空对象之外的独立对象都不是有效的 JS,所以如果你 return

{"name": "John Smith", "email":"email@mail"}

攻击者最终得到 SyntaxError: missing ; before statement 或类似的东西。

更多信息http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/

  1. What does it mean by this? And here, what does it mean by JSON output? And why to wrap it in a dictionary?

    All JSON output should be wrapped in a dictionary.

正如您在上面所读到的,很明显,JSON 中的 top-level 元素不应该是 array。此外,如果你传递 list,Tornado 会引发错误。当然你可以绕过这个安全,简单地传递字符串(json 在 wirte 之前转储),但这并不明智:

self.write('["this", "is", "wrong"]')
  1. a. What is the best way to send JSON responses from Tornado to client?

    b. What is a better way to send responses? If not JSON, then what is? And if it JSON, then just mention the answer to subpart (a).

如果可能,我会使用 json 或 xml 作为回应。但是我没有为此使用 Tornado 的机制,我将已经编码的对象 - 字符串传递给 write。原因是,这是覆盖 Tornado 编码器并使用例如的最干净的方法。 ujson.

编辑

值得注意的是 modern browsers should not vulnerable