I am using AJAX to generate actions on my website. For example, a "sea开发者_运维技巧rch results page" calls Ajax which initiates "/getResults.php". This PHP file returns a JSON with 20 entries that contains the results. The HTML Page calls the callback function and re-builds the DOM with the results from the JSON.
It thus seems inevitable that using Ajax in this form will result public API (just send "/getResults.php" a request with a query and you will get easy to use JSON).
Is there anyway to block these Ajax calls? This is more acute when setting database entries, and not only retrieving.
Thanks,
Joel
Since the "API" will have to be accessible via normal HTTP requests, it's by definition "public". But, it is playing by the same rules as all other HTTP requests as well. Somebody could submit POST requests to your form submission pages without actually using your site, which is the exact same problem. You can secure your AJAX calls the same way you'd secure your POST submissions; i.e. not at all, or by requiring cookies, or by requiring some special token, or by applying IP filtering or throttling, etc. pp.
You could use nonces or short-lived CSRF token. Write it into the page and the session and pass it back with your requests. This adds a little bit of impedance, but anyone that's really determined to get your data won't have much of a problem doing so, since they could just screen-scrape a token to use in their own requests.
Why are you wanting to protect those interfaces, and how important is it that people not be able to get access to them outside of your app? If it's really critical that you protect that data, you'll need to go with a solution that isn't client-driven, which unfortunately means no AJAX, as you're likely well aware.
No, a public json api needs to return the json wrapped in a javascript function, known as jsonp. You are fine if you return just a json object.
From the jQuery .load() function description
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
No. You're sort of creating a public API.
There may be ways witch make it harder to use your API, obfuscation of your code in combinisation with some sort of checksum that only you know how to correctly create.
When writing data to the server you should always authenticate the user anyway. The same system that works for your page now should work for your AJAX calls. (Cookies, HTTP Authentication, ...)
One rudimentary level of 'protection' is to check the HTTP_REFERER
header on your server to make sure the request is coming from your own website. This can be spoofed, though, so I wouldn't trust it too much.
精彩评论