If you’re unfamiliar with JSON Hijacking, I suggest you first take a gander at the StackOverflow question “Why does Google prepend while(1); to their JSON responses?”. The crux of the problem is that in older browsers, a vulnerability exists whereby an attacker can insert a
<script> tag which triggers a
GET request to a valid endpoint of your RESTful API on behalf of the client. Attackers can then override the global array constructor or accessor methods to steal your data. Again, this is only in older browsers, but you still want to err on the side of caution.
Solution 1: Don’t Allow GET Requests
The simplest solution is to disallow GET requests to your API altogether. Problem solved, but not necessarily best practice for developing a RESTful service.
Solution 2: Prefix an Arbitrary Tag to Your JSON and JSONP Responses
The alternative solution is to prepend your API responses with an arbitrary tag that doesn’t allow the JSON to be eval’ed. Examples of possible tags include, but are not limited to:
So this would solve our server side problems, but we now have a client side issue with how to parse malformed JSON or JSON-P. Lucky for us, jQuery already has a method
dataFilter to handle filtering our AJAX response data prior to JSON decoding it:
This above example will attempt to remove the three prefixes mentioned earlier from the AJAX response. Simply add this block of code following your jQuery include and before your trigger any AJAX requests and you should be all set!