Search code examples
jsonpsame-origin-policycross-site

Why is cross-domain JSONP safe, but cross-domainJSON not?


I'm having trouble connecting some dots having recently learned of JSONP. Here's my understanding:

  • Cross-domain XmlHttpRequests for any content (including JSON) is banned, due to the same origin policy. This protects against XSRF.
  • You are permitted to have a script tag with a src that returns JSONP - some JSON padded inside a call to a Javascript function (say 'Foo')
  • You can have some implementation of 'foo' on the page that will get called when the JSONP data is returned, and you can do things with the JSON data that function is passed

Why is it OK to receive cross-domain data if it came via JSONP, but not if it came via JSON?

Is there an assumption that JSON is prone to permitting XSRF but JSONP is not? If so, is there any reason for that other than JSONP being some de-facto data format that won't ever provide data that enables XSRF? Why JSONP and not some arbitrary root tag on XML instead?

Thank you in advance for your answers, please make my brain work again after failing to figure this one out.


Solution

  • I don't know how the perception that JSONP is safe came up but see

    JSON-P is, for that reason, seen by many as an unsafe and hacky approach to cross-domain Ajax, and for good reason. Authors must be diligent to only make such calls to remote web services that they either control or implicitly trust, so as not to subject their users to harm.

    and

    The most critical piece of this proposal is that browser vendors must begin to enforce this rule for script tags that are receiving JSON-P content, and throw errors (or at least stop processing) on any non-conforming JSON-P content.

    both quotes from http://json-p.org/ .

    other links with some useful information about JSONP/security:

    all these tell 2 things - basically it is not considered "safe" but there are ideas on how to make it "safer"... though most ideas rely on standardization AND specific check logic to be built into browsers etc.