views:

337

answers:

5

When requesting (ht|x)ml with ajax you can only send requests to the same domain. But if you request JSON you can send it to any domain. Why?

I'm told it's for security but why would a website do something malicious via ajax rather than just directly if that makes sense.

+1  A: 

Check out this wikipedia article.

The reason why JSON is 'safe' is because you have to pass it through a callback. The remote site will run return JSON and your javascript library will not just run it blindly but try to pass it to a function you specify, like jsonpCallback( response ). Since you aren't running the remote code directly much more is under your control and all is mostly well in the world.

thenduks
An eval is run by the browser on the JSON before it enters your callback function. This eval'ed code can even rewrite your callback function before it is called.
Mic
I don't run eval on JSON responses, I use a parser.
thenduks
You don't have the choice on that, the browser will interpret the JSON string response and convert it to an object before it enters your function. So it is not safe at all.
Mic
+1  A: 

becaues in the case of ajax, clients computer makes the call, so i could make a 1000 different computers on the net attack to a specific website (or do something else, digg my website, vote for me for us presidency). And it wouldnt be tracable or stoppable because it would act like 10000 different people.

marvin
+3  A: 

The reason it's called JSONP has actually little to do with JSON itself. Doing a cross-domain ajax request is as simple as adding the <script src="http://url.com/data.js&gt;&lt;/script&gt; tag to your HTML web page; this is the base concept of JSONP and cross-domain ajax.

What happens is that the data.js file is interpreted by JavaScript. This gives us the ability to get data from that data.js file (which is located on another domain), if for example it loads a function that is available in the current scope.

Luca Matteis
A: 

Injecting JSON directly in your page is not secure at all.

You offer to the loaded scripts full access to the resources in your page(data, cookies, logic).

If the injected code is malicious, it can run actions on your server, post back data to their server(POST is allowed cross domain, not the response but your data are sent anyway), etc...

We're building a web app that makes a heavy use of cross domain accesses.
To solve this problem, we came with a rather simple JSONP sandboxing solution.

Mic