Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

From what I understand, the JSON-P technique generates a script tag into the DOM

ID: 661267 • Letter: F

Question

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?

Explanation / Answer

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote