Saturday 4 January 2014

JSONP in a nutshell

JSONP In a Nutshell 

is basically a way invented to get around the Single Origin Policy, thus allowing the user access to resources that that comes from another domain.

It came about BEFORE the introduction of CORS, which is the proper non hacky way of accessing cross origin resources.  (This is a guess .. I don't see why JSONP will be needed if CORS existed before it.)

How does it work?
Assuming I run a website (www.mysite.com) and I want to access a RESTFul resource on another site (www.othersite.com/user/1234) which returns some JSON:

{
  userId : 1234,
  userName : 'Jeff'
}

Without using CORS, there are actually no way for me to do this.

So some clever people figured out that since script tags are exempt by the brower from Single Origin Policy.  They can use a script tag like this to load the resource:

<script src="www.othersite.com/user/1234" type="application/javascrpt" ></script>

to try and load the resource.
However this doesn't work.  The script just gets evaluated, but you cant actually do anything with the resource, and this is where JSONP comes in.

By telling the server, to wrap the response in a javascript function that YOU want it to call when the script is evaluated, you now effectively can access the cross origin resource!

For example:

<script src="www.othersite.com/user/1234?callback=executeMe" type="application/javascrpt" > </script>

The server can be configured to return the following when it sees the callback request param:

executeMe({
   userId : 1234,
  userName : 'Jeff'
});

and when this is sent to the browser, it will be evaluated and your executeMe function will be executed with the cross origin data that you requested for!

* executeMe will be a function that's already defined on your page.

Summary

  • Its pretty much a hack to work around Same Origin Policy.  Should just use CORS now...
  • The server side needs to implement this.  I.e. its NOT like I can use JSONP to access any resource on the web I want.  (Its NOT a hacking tool ..)
  • If you are using JSONP to serve up some data, then your server is vulnerable, because anyone now can access that resource (unless you protect it some other way ..)  

1 comment:

  1. nice explanation, I guese it would be typical to call `eval( jsonpResponse)`. Kind of scary that the jsonp can execute any arbitrary JavaScript.

    ReplyDelete