This is quite a simple question – although one that is on my mind right now as I start my first real-world and quite grand (in terms of size) project.
How would I go about verifying a user’s identity (username and password) when the send an Ajax request via PHP? It seems like there is a simple solution: to send both the username and password as POST variables along with the others in the request but it seems to me that solution is quite inefficient (as it has to check in the database every single time a request is made and be quite redundant for different Ajax requests).
I looked into how Twitter does their Ajax requests (such as for posting a new tweet) and I don’t see them sending any authentication information in the request – but how do they know that it is in fact me, the owner of my profile, sending the Ajax request to post the new tweet?
If it helps anyone come up with a great solution – I am using the JQuery AJAX library and the CodeIgniter PHP framework.
Thanks!
Ajax requests are exactly the same as any other HTTP request. Whether it’s done via JavaScript or by typing a URI into your browser’s address bar, they are all HTTP requests.
You are right that sending the username and password over HTTP is the wrong solution. However, sending the username/password is usually necessary once but this should only be done on HTTPS, so that it isn’t sent as plain text. Once authenticated, you can store the user ID in a server-side session variable for access in future requests.
A little pseudo-code to help you along the way:
A common pitfall is to store authentication in a cookie. Cookies are stored on the client side, so if you do it this way anyone could forge authentication by creating their own cookies.
Using session variables in PHP, a cookie is used, however it doesn’t identify the user at all, rather identifies the connection between the client and the server.
But to successfully authenticate real-world projects, session cookies should not be relied upon. Rather, a combination of a session variable, a UUID cookie and a salted hash cookie can increase integrity of authentication… but this is another topic altogether.