Search code examples
phpjquerysecuritycsrf

CSRF protection in PHP


I have some PHP POST scripts that I need to protect from CSRF attacks and have multiple questions:

1) If I submit POST requests to PHP using jquery without an HTML form, just be getting values directly from the HTML elements and submit them using jquery, am I still at risk of CSRF?

2) When a user logs in to website, I store their unique token in a session variable. In the PHP POST script I check if that session variable is set and has the same value I set before. Isn't that enough? why is it needed for the token to be included in the HTML form as well?

Thanks


Solution

    1. Yes. It doesn't matter how you construct the request, the attacker can construct one in the same way. (In theory you could make features of a complex request (which would trigger a CORS preflight request) mandatory, so that another site couldn't get the user's browser to duplicate the whole request, but I wouldn't want to depend on that).
    2. No

    The point of the token is to check that the page which contains the code responsible for deciding what goes in the request (i.e. the form or the JavaScript) is a page on your website.

    If the form (or JavaScript) can read a token (which matches the one in the session) from the HTML of the page and put it in the request, then you know the code that constructed the request came from your site.

    If you just check that it is in the session, then all you are checking is that the user has caused a token to be generated (which usually just means visiting any page on your site… which could be in a hidden frame).