API jQuery

Authored by Corey Ballou

1 Comment

Safely Handling JSON Hijacking Prevention Methods with jQuery

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:

  • //
  • while(1);
  • for(;;);

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!

Author: Corey Ballou

Corey Ballou is the CEO of Whether you're a student, young professional, entrepreneur, startup, or small business, you can be up and online fast with your own custom domain, email, and webpage on POP. Corey is a professional PHP developer by trade, specializing in custom web applications development for startups, small businesses, and agencies. Follow Corey on Twitter @cballou.

  • Mark

    You dont need an indexof, it should be faster with substr.