0

I have a web application that consists of a JavaScript frontend and a backend built with PHP, where the frontend makes some AJAX requests to the backend's URL, for example: api.examplesite.com?q=some_query and the results are returned back in JSON format.

Anyone who knows this URL, could directly call it and get the same results.

What is the best practice to make this URL unreachable from third parties, but still working for my application?

Vassilis Barzokas
  • 3,105
  • 2
  • 26
  • 41

4 Answers4

2

Any URL available for an AJAX call is available to the public web. To keep it "private" you can tie it to a user session or token, which you would initiate on your main page and persist across AJAX calls.

Also, if "some_query" is an actual SQL statement, this is considered extremely bad practice for an AJAX call. Your SQL should only be directly available on the server side, not any arbitrary client.

Matt S
  • 14,976
  • 6
  • 57
  • 76
-1

Actually there is no way for doing this. Your application is client side, so it need to get response from server. It means that it can be intercepted by client anyway.

You can use encryption to prevent someone who intercepted the data to be able to read it. You can use either symmetric cipher and hard code some key in the client side app (which is not good, because if the key is compromised then all traffic from all your clients can be decrypted) or you can use SSL/TLS for communicating with the server (which I think is the best solution if you transferring sensitive information).

Alex Amiryan
  • 1,374
  • 1
  • 18
  • 30
  • 1
    The question is how to prevent any arbitrary requests to his AJAX URLs, not how to secure the information during the requests. – Matt S Aug 13 '12 at 14:13
-1

The client has to be able to request the URL to use it. However, you could check to see if the request was made with ajax, and then return the information accordingly:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
    AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
   // I'm AJAX!
}

Check this out for more info

Community
  • 1
  • 1
cmac
  • 3,123
  • 6
  • 36
  • 49
  • 1
    this approach may not serve the purpose of **security**... first of all... an attacker may write his own application in ajax... secondly, one can fake an ajax request by injecting the appropriate header into the http request... – user1055604 Dec 25 '12 at 19:01
-3

For security, you can try and force the numeric types or quote the strings BEFORE executing the query.

e.g.

$number = (int) $number;
$string = htmlspecialchars($string);

Oh right, for the answer: there is no way to make it unreachable.

Andrei Cristian Prodan
  • 1,114
  • 4
  • 17
  • 34