views:

589

answers:

4

What's the best practice for making sure that certain ajax calls to certain pages are only accepted from authenticated users?

For example:

Let's say that I have a main page called blog.php (I know, creativity abounds). Let's also say that there is a page called delete.php which looks for the parameter post_id and then deletes some entry from a database.

In this very contrived example, there's some mechanism on blog.php which sends a request via ajax to delete.php to delete an entry.

Now this mechanism is only going to be available to authenticated users on blog.php. But what's to stop someone from just calling delete.php with a bunch of random numbers and deleting everything in site?

I did a quick test where I set a session variable in blog.php and then did an ajax call to delete.php to return if the session variable was set or not (it wasn't).

What's the accepted way to handle this sort of thing?

+4  A: 

You were correct in trying to use session variables. Once your user authenticates, you should store that information in their session so that each subsequent page view will see that. Make sure you are calling session_start() on both pages (blog.php and delete.php) before accessing $_SESSION. Also make sure you have cookies enabled -- and if not, you should pass an additional parameter in the query string, usually PHPSESSID=<session_id()>.

pix0r
A: 

@pix0r

Hmmm. I thought I was calling session_start() on both pages but I'm clearly doing something wrong.

Let me go and double-check my session code.

Mark Biek
A: 

OK. I must have been crazy the first time I tried this.

I just did another test like the one I described above and it worked perfectly.

Mark Biek
+1  A: 

It is not recommended that you rely on sessions for authentication without taking additional actions. Read more on http://shiflett.org/articles/the-truth-about-sessions.

Andy