How do I restrict JSON access?

I have a web application that pulls data from my newly created JSON API.

My static HTML pages dynamically calls the JSON API via JavaScript from the static HTML page.

How do I restrict access to my JSON API so that only I (my website) can call from it?

In case it helps, my API is something like: http://example.com/json/?var1=x&var2=y&var3=z... which generates the appropriate JSON based on the query.

I'm using PHP to generate my JSON results ... can restricting access to the JSON API be as simple as checking the $_SERVER['HTTP_REFERER'] to ensure that the API is only being called from my domain and not a remote user?


The usual method for restricting access to your domain is prepend the content with something that runs infinitely.

For example:

while(1);{"json": "here"} // google uses this method
for (;;);{"json": "here"} // facebook uses this method

So when you fetch this via XMLHttpRequest or any other method that is restricted solely to your domain, you know that you need to parse out the infinite loop. But if it is fetched via script node:

<script src="http://some.server/secret_api?..."></script>

It will fail because the script will never get beyond the first statement.


I think you might be misunderstanding the part where the JSON request is initiated from the user's browser rather than from your own server. The static HTML page is delivered to the user's browser, then it turns around and executes the Javascript code on the page. This code opens a new connection back to your server to obtain the JSON data. From your PHP script's point of view, the JSON request comes from somewhere in the outside world.

Given the above mechanism, there isn't much you can do to prevent anybody from calling the JSON API outside the context of your HTML page.


In my opinion, you can't restrict the access, only make it harder. It's a bit like access-restriction by obscurity. Referrers can be easily forged, and even with the short-lived key a script can get the responses by constantly refreshing the key.

So, what can we do?

Identify the weakness here:

http://www.example.com/json/getUserInfo.php?id=443

The attacker now can easily request all user info from 1 to 1.000.000 in a loop. The weak point of auto_increment IDs is their linearity and that they're easy to guess.

Solution: use non-numeric unique identifiers for your data.

http://www.example.com/json/getUserInfo.php?userid=XijjP4ow

You can't loop over those. True, you can still parse the HTML pages for keys for all kinds of keys, but this type of attack is different (and more easily avoidable) problem.

Downside: of course you can't use this method to restrict queries that aren't key-dependent, eg search.

链接地址: http://www.djcxy.com/p/47788.html

上一篇: 学习Ruby on Rails

下一篇: 我如何限制JSON访问?