반응형

JSONP

From Wikipedia, the free encyclopedia

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of thesame-origin policy.

Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results. The JSONP parameters passed as arguments to a script are defined by the server.

Reason for JSONP[edit]

Under the same-origin policy (SOP)JavaScript code loaded from one domain is not allowed to fetch data from another domain. However, this restriction does not apply to the <script> tag, which can specify a URL of JavaScript code to load from a remote server in a src attribute. This was used to work around the SOP limitations by pointing the src to aweb service returning dynamically generated JavaScript code (JSONP), instead of JSON data. Because the code is loaded by the <script> tag, it can be normally executed and return the desired data block, thus bypassing SOP.

Execution of raw JavaScript from a third party raised security concerns and creates a possible vulnerability.[1] 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. All modern browsers now support CORS making it a viable cross-browser alternative.

How it works[edit]

To see how this technique works, first consider a URL request that returns JSON data. A JavaScript program might request this URL via XMLHttpRequest, for example. Suppose the user ID of Foo is 1234. A browser requesting the URLhttp://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="application/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 were 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[2] 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="application/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.[3][4][5]

The dynamically injected script element for a JSONP call looks like this:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</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.

The script runs within the scope of the including page and, as such, is still subject to cross-domain restrictions relative to the including page's domain. This means that one cannot, for example, load a library hosted on another site via JSONP and then make XMLHttpRequest requests to that site (unless CORS is supported) although one could use such a library to make XMLHttpRequests to one's own site.

Cross-domain requests using a proxy server[edit]

The JavaScript same-origin policy normally prevents browsers from sending AJAX requests to a different domain and receiving a response (newer browsers that support CORS can relax this constraint). A cooperating proxy server, however, does not have such restrictions and can relay a browser request to a server in a separate domain, store the result, and then return that JSON payload when the browser makes a second request. The server would be instructed within the first request to store the output (POST returning JSON payload) temporarily into a local store (for example memcached or within a session variable), and a second request from the browser then would fetch the cached response to the initial query.[6] The xd_arbiter.php used by Facebook's JS SDK is a popular example of this cooperating server technique.[7]

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. If an attacker can inject any JavaScript into the original web page, then that code can retrieve additional JavaScript from any domain. The Content Security Policy HTTP Header lets web sites tell web browsers which domains scripts should be included from.

An effort is underway to define a safer strict subset definition for JSON-P[8] 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.[9]

Cross-site request forgery[edit]

Native deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks.[10] 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.[11][12] The original proposal for JSONP, where the padding is a callback function, appears to have been made by Bob Ippolito in December 2005[13] and is now used by many Web 2.0 applications such as Dojo ToolkitGoogle Web Toolkit 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.

See also[edit]

References[edit]

External links[edit]


Posted by 1010