Search code examples
phpjavascriptjqueryajaxcsrf

How to Implement Generic CSRF Tokens with JQuery AJAX?


I am currently developing jquery code that sends data to the server via ajax that is then inserted into the database based on the request parameters.

However, I am rather concerned that this could be abused by CSRF attacks which would make things rather insecure. I have tried to research this and only find answers for specific frameworks such as django and rails where I am only after a generic implementation for use with PHP.

I have read that you can use the JQuery.ajaxsend() function to implement the code so that a token is sent with EVERY AJAX request however I have no idea how this can be implemented as JavaScript obviously has no access to the PHP session variables. Would the use of cookies be secure enough?

Basically I need to be able to check the origin of the request to ensure that the request is genuine and not a forged request used to take advantage of the system.

If anyone can point me in the right direction that would be most appreciated!


Solution

  • Well, do know that $.ajax seems to send the cookies, including the PHP session cookie, with its request. Using that feature changes your attack from CSRF to session hijacking, but it's a start. Next, run your service over SSL if you can to avoid the session hijacking.

    I'm sure there are other ways to do this as well, but for vanilla PHP, this seems to work. Someone correct me if I'm wrong, please.