Page 1 of 1

Preventing unwanted ajax requests to a low-level REST API

Posted: Sun Jan 01, 2012 10:16 am
by jraede
Let me start by saying that I'm self taught, and thus, while I consider myself a fairly advanced programmer, I'm fairly lacking in knowledge on security.

I'm developing a REST API that for now only processes and serves information if the request comes from the same domain as the server. I'd like to be able to limit any requests to this API to ones that come directly from programmed JavaScript, and prevent any requests that are run from, for instance, the console, or from JavaScript typed into the URL bar.

I've read about using tokens generated server-side, passing them as a JavaScript variable, and then sending them along with the AJAX request, but if I were really trying to abuse the system, I would just go into the page source, find where the variable is set, and then use that token in an abusive request.

What am I missing in this process? How can I truly ensure that a request is valid? Should I rethink my approach?

Thanks.

Re: Preventing unwanted ajax requests to a low-level REST AP

Posted: Mon Jan 02, 2012 1:34 am
by Christopher
You can check if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') to see if a request is and Ajax call. But neither that or the domain check are reliable security as those values can be spoofed.

Re: Preventing unwanted ajax requests to a low-level REST AP

Posted: Mon Jan 02, 2012 9:27 am
by jraede
So what is a good way to validate the authenticity of AJAX calls? Is there some "common practice" that I haven't found?

Re: Preventing unwanted ajax requests to a low-level REST AP

Posted: Tue Jan 03, 2012 12:56 am
by Christopher
You can't -- so you need to validate, filter and escape all incoming data and data being displayed that is from a source that may contain untrusted data, such as a database.

Re: Preventing unwanted ajax requests to a low-level REST AP

Posted: Tue Jan 03, 2012 3:36 am
by Weirdan
Security-wise you can not trust a code running in an environment you don't control (such as client's browser), regardless of the code origin. Treat that code as you would any other external client: if it obeys the rules and follows the protocol you shouldn't really deny it any access.