Tuesday, August 13, 2013

REST API callback

A callback is something that you wrap the response of an API call with such as a javascript function. This is typically supported by GET API calls only.
To make a REST call from a web browser across domains, we can use JSONP.
JSONP or JSON with padding provides a method to request data from a server in a different domain. This was previously prohibhited to ensure same origin policy but has since been addressed with Cross-Origin resource sharing (CORS). The same origin policy was overridable with the script tag in HTML5. Some pages use the script tag to retrieve Javascript code that operates on dynamically generated JSON from different origin.
So you can have a script like so:
<script src="your_api_call?callback=printResponse" /> This is the cross domain access supported by JSONP.
Each new JSONP request comes with its own script element or reuses an existing one. In the former case, when the script element is newly added to the document object model, it is referred to as the script element injection.  The current mime type supported by JSONP is "application/javascript". There has been discussion to make it more strict with "application/JSON-P"
Cross site request forgery or xsrf attack is often considered a vulnerability in making cross domain calls, however this is avoided by not using callbacks for sensitive data or using callbacks only with same origin for such data. This enforces that the sensitive data is not in the open unless the request is proper. When programmers rely on cookies alone to determine if the request is valid, it is often vulnerable to cross site request forgery.
In cross origin resource sharing , the website accepting cross domain requests sends an Access-Control-Allow-Origin in its response. The values of the headers indicate which sites are allowed.  To allow access from all site a Access-Control-Allow-Origin : * can be specified. However, this is not advisable unless the API is public with non-sensitive data.
The difference between CORS and JSONP is that JSONP only supports GET methods where as CORS supports other methods. Another difference is that JSONP causes XSS issues when external site is compromised. However, CORS allows websites to manually parse responses to further improve security.
Web messaging or cross domain messaging is used when documents communicate with one another across domains. Here the postMessage method in the messaging API and retrieving the window object of the receiving document, plain text data can directly be posted in an iFrame. The message usually carries the following three attributes : data or the actual content, the origin of the sender and lastly the source or the WindowProxy where the document came from. Window has addEventListener method to receive messages.
Courtesy : Wikipedia.

No comments:

Post a Comment