Hack to Prevent JSON Hijacking

JSON hijacking

I recently needed to ensure a JSON service response couldn’t be misused via external JSON hijacking. This is a very common problem, especially in older browsers. Fortunately, there’s a nice little hack to prevent the hijack.

Microsoft, Google, Facebook etc are all using variations of this to allow AJAX requests on their (same) domain to have full access, while preventing hijacking by others.

The hack

Force requests not to use JSONP and allow the Same Origin Policy to do it’s job, by adding a simple (and evil) endless loop to the start of a JSON response:

1
while(1);

Because you aren’t using a JSONP request, you have the ability to modify the response, e.g.

1
JSON.parse(this.responseText.slice("while(1);".length));

Whereas illegitimate users will find themselves sucked into a black hole.

Facebook use a similar variation to achieve the same result:

1
for(;;);

Personally, I’d like to lead the JSON response with the throwing of an error message :)

1
throw "JSON THIEF";

Limitations

Using this quick and easy hack means you don’t need to mess around storing and managing CSRF (cross-site request forgery) tokens. Winning. It’s not however a solution for cross-site request forgery itself. Maybe I’ll cover that on another, less sunny day.