Ajax and CSRF protection

Yes, you could do this. This should be fine. It is a reasonable defense against CSRF.

Do make sure that side-effecting actions can only happen via POSTs (never via GET), and that all POSTs check for the presence of the token. Also, make sure you generate the token as a cryptographically-strong pseudorandom number (e.g., using CryptGenRandom(), /dev/urandom, SecureRandom, or similar) and store it in session state.

I don't know if this has any benefit over, say, cookie double-submission -- but you could do it, and it should protect against CSRF successfully.


Really, two requests for each task is a performance overhead. You can simply achieve this using single request. You can simply validate the token during POST request, and send back the new token with each request. Using JS make sure you pick up the latest cookie value and attach it to every request AJAX sent.

In fact if you want to cut off your pain in CSRF protection of your web application, you can see OWASP CSRF Protector Project, (available for php only currently), it does everything required, to mitigate CSRF and works well with AJAX (both XHR and activeXObject)

Tags:

Ajax

Csrf