Is getting JSON data with jQuery safe?

后端 未结 4 1106
天涯浪人
天涯浪人 2021-02-09 04:30

JSON allows you to retrieve data in multiple formats from an AJAX call. For example:

$.get(sourceUrl, data, callBack, \'json\');

could be used

相关标签:
4条回答
  • 2021-02-09 04:34

    Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.

    0 讨论(0)
  • 2021-02-09 04:35

    All browsers I know of disable cross-site requests through Ajax. That is, if your page sits on my.example.com, you can't load anything using Ajax unless its URL is also at my.example.com.

    This actually can be something of a nuisance, and there are ways for an attacker to inject source in other ways, but ostensibly this restriction is in place to address exactly the concern you mention.

    0 讨论(0)
  • 2021-02-09 04:37

    $.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).

    From Douglas Crockford site about The Script Tag Hack (jsonp):

    So the script can access and use its cookies. It can access the originating server using the user's authorization. It can inspect the DOM and the JavaScript global object, and send any information it finds anywhere in the world. The Script Tag Hack is not secure and should be avoided.

    0 讨论(0)
  • 2021-02-09 04:51

    The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.

    Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.

    You can find such a function at https://github.com/douglascrockford/JSON-js/blob/master/json2.js.

    See JSON and Broswer Security for a good discussion of this area.

    In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.

    NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:

    As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback.

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