javascript - Why shouldn't the server respond with a JSON Array?

后端 未结 2 596
醉话见心
醉话见心 2021-01-28 15:29

According to this Angular 2 guide:

Don\'t expect the decoded JSON to be the heroes array directly. This server always wraps JSON results in an object wit

相关标签:
2条回答
  • 2021-01-28 16:12

    This was rather bad advice that has since been removed from the angular tutorial.

    1. The linked OWASP Cheet Sheet lists three ways to defend against JSON Hijacking. The one the tutorial picked is the hardest to implement correctly, because one must educate every single developer, and audit every single REST resource, rather than writing a single HttpInterceptor to extend CSRF-defenses to GET requests.
    2. JSON hijacking can only occur due to browser bugs, which tend to be fixed quickly (this does not imply such attacks are impossible, but the easy exploits no longer work in modern browsers)
    0 讨论(0)
  • 2021-01-28 16:16

    To avoid JSON Hijacking:

    The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.

    For example, if you had a JavaScript file that contained the following JSON: {“Id”:1, “Balance”:3.14} And you had a script tag that referenced that file: <script src="http://example.com/SomeJson"></script>

    You would get a JavaScript error in your HTML page. However, through an unfortunate coincidence, if you have a script tag that references a file only containing a JSON array, that would be considered valid JavaScript and the array gets executed.

    So allowing JSON to be returned as anything but an object would make it possible to return a JSON array that contained code that could be run on the client level (in a context where the client isn't expecting it to be runnable, could be malicious, etc). Only returning JSON objects prevents this from happening.

    0 讨论(0)
提交回复
热议问题