JSONP
JSONP or "JSON with padding" is a communication technique used in JavaScript programs which run in Web browsers. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.
Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. A few exceptions include the HTML <script> element. Exploiting the open policy for <script> elements, some pages use them to retrieve JavaScript code that operates on dynamically generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.
There have been some criticisms raised about JSONP. Cross-origin resource sharing (CORS) is a more recent method of getting data from a server in a different domain, which addresses some of those criticisms.
Contents |
How it works[edit]
To see how this pattern works, first consider a URL request that returns JSON data. A JavaScript program might request this URL via XMLHttpRequest, for example. Suppose the UserId of Foo is 1234. A browser requesting the URL http://server2.example.com/Users/1234, passing the Id of 1234, would receive something like:
{ "Name": "Foo", "Id": 1234, "Rank": 7 }
This JSON data could be dynamically generated, according to the query parameters passed in the URL.
Here, an HTML <script> element specifies for its src attribute a URL that returns JSON:
<script type="text/javascript" src="http://server2.example.com/Users/1234"> </script>
The browser will, in order, download the script file, evaluate its contents, interpret the raw JSON data as a block, and throw a syntax error. Even if the data was interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment object literals are inaccessible.
In the JSONP usage pattern, the URL request pointed to by the <script>'s src attribute returns JSON data, with a function call wrapped around it. In this way, a function that's already defined in the JavaScript environment can manipulate the JSON data. A JSONP payload might look like this:
functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});
The function call is the "P" of JSONP - the "padding" around the pure JSON, or according to some[1] the "prefix". By convention, the browser provides the name of the callback function as a named query parameter value, typically using the name jsonp or callback as the named query parameter field name, in its request to the server, e.g.,
<script type="text/javascript" src="http://server2.example.com/Users/1234?jsonp=parseResponse"> </script>
In this example, the received payload would be:
parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
Padding[edit]
While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other JavaScript statement. The response to a JSONP request is not JSON and is not parsed as JSON; the returned payload can be any arbitrary JavaScript expression, and it does not need to include any JSON at all. But conventionally, it is a JavaScript fragment that invokes a function call on some JSON-formatted data.
Said differently, the typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call.
Script element injection[edit]
JSONP makes sense only when used with a script element. For each new JSONP request, the browser must add a new <script> element, or reuse an existing one. The former option - adding a new script element - is done via dynamic DOM manipulation, and is known as script element injection. The <script> element is injected into the HTML DOM, with the URL of the desired JSONP endpoint set as the "src" attribute. This dynamic script element injection is usually done by a JavaScript helper library. jQuery and other frameworks have JSONP helper functions; there are also standalone options.[2][3][4]
The dynamically injected script element for a jsonp call looks like this:
<script type="text/javascript" src="http://server2.example.com/Users/1234?jsonp=parse_Response"> </script>
After the element is injected, the browser evaluates the element, and performs an HTTP GET on the src URL, retrieving the content. Then the browser evaluates the return payload as JavaScript. This is typically a function invocation.
In that way, the use of JSONP can be said to allow browser pages to work around the same origin policy via script element injection.
Security concerns[edit]
Including script tags from remote servers allows the remote servers to inject any content into a website. If the remote servers have vulnerabilities that allow JavaScript injection, the page served from the original server is exposed to an increased risk.
An effort is underway to define a safer strict subset definition for JSON-P[5] that browsers would be able to enforce on script requests with a specific MIME type such as "application/json-p". If the response didn't parse as strict JSON-P, the browser could throw an error or just ignore the entire response. For the moment however the correct MIME type is "application/javascript" for JSONP.[6]
Cross-site request forgery[edit]
Naive deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks.[7] Because the HTML <script> tag does not respect the same origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.
This is problematic only if the JSON-encoded data contains sensitive information which should not be disclosed to a third party, and the server depends on the browser's same origin policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.
History[edit]
In July 2005 George Jempty suggested an optional variable assignment be prepended to JSON.[8][9] The original proposal for JSONP, where the padding is a callback function, appears to have been made by Bob Ippolito in December 2005[10] and is now used by many Web 2.0 applications such as Dojo Toolkit, Google Web Toolkit,[11] and Web services.
An unnamed process equivalent to JSONP has been used by PostX envelopes (now owned by Cisco Systems and deployed on Cisco's Email Security Appliance and Cisco Registered Envelope Service (CRES)) since May 2002.
References[edit]
- ^ "Experimental RDF result set to JSON translator". Retrieved February 20, 2012.
- ^ "example jsonp library on pastebin".
- ^ "Basic JSONP helper (pure JS)".
- ^ "jQuery's $.getJSON utility".
- ^ "Safer cross-domain Ajax with JSON-P/JSONP". JSON-P.org. Retrieved 30 October 2011.
- ^ Grey, Eli (2010-06-27). "Is this safe for providing JSONP?". stackoverflow.com. Retrieved 2012-09-07.
- ^ Grossman, Jeremiah (January 27, 2006). "Advanced Web Attack Techniques using GMail". Retrieved July 3, 2009.
- ^ "eval'ing JSON". July 19, 2005.
- ^ "json: Message: Re: Comments". August 17, 2005.
- ^ "Remote JSON - JSONP". from __future__ import *. Bob.pythonmac.org. December 5, 2005. Retrieved September 8, 2008.
- ^ "GWT Tutorial: How to Read Web Services Client-Side with JSONP". Google Web Toolkit Applications. February 6, 2008. Retrieved July 3, 2009.