1

From what I understand, the JSON-P technique generates a script tag into the DOM of an HTML page to get across the single-origin restrictions imposed on the XMLHttpRequest JavaScript API for AJAX calls to web services not supporting CORS. Usually, the script embedded in this way only contains a callback and in this way transfers the JSON payload that I'm interested in. However, AFAIK the called JSON-P service could also deliver arbitrary JavaScript and in this way hijack my webpage.

I'm wondering if I really have to trust the JSON-P service provider not to do this? Or do JavaScript libraries and/or browsers sanitize the JSON-P responses and in this way prevent these kind of attacks?

For example for the JQuery ajax function, the use of JSON-P is enabled by setting the rather harmlessly looking attribute dataType: 'jsonp' - so maybe these kind of calls are not as bad as I think they are?

Anders
  • 64,406
  • 24
  • 178
  • 215
oberlies
  • 113
  • 5
  • 1
    json-p is essentially XSSing yourself, and I honestly wouldn't be surprised if the browsers shut it down in the future. If you want to use an external api, don't even subdomain them, just do mydomain.com/facebook/ and redirect that route to the service. – Andrew Hoffman Jul 10 '14 at 18:00

1 Answers1

3

No it is not safe. You are correct that the JSONP service could deliver arbitrary JavaScript, which is then executed as part of your site.

Because JSONP is essentially a hack to get around the same origin policy, it is not possible for a JavaScript framework to perform sanitisation.

These days, CORS is the preferred way to call external sites. An alternative approach is to have a server-side script on your site that proxies calls to external sites.

paj28
  • 32,736
  • 8
  • 92
  • 130