Preventing unwanted ajax requests to a low-level REST API

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
jraede
Forum Contributor
Posts: 254
Joined: Tue Feb 16, 2010 5:39 pm

Preventing unwanted ajax requests to a low-level REST API

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

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

Post 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.
(#10850)
jraede
Forum Contributor
Posts: 254
Joined: Tue Feb 16, 2010 5:39 pm

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

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

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

Post 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.
(#10850)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

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

Post 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.
Post Reply