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.
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:
Because you aren’t using a JSONP request, you have the ability to modify the response, e.g.
Whereas illegitimate users will find themselves sucked into a black hole.
Facebook use a similar variation to achieve the same result:
Personally, I’d like to lead the JSON response with the throwing of an error message :)
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.