Preventing CSRF requires three things:
- Make sure your forms use POST
- Make sure your site is not vulnerable to XSS
- Make your forms use a CSRF key
Step 1 isn’t really a requirement – you could CSRF protect forms which use GET too, but it’s generally a bad idea to have forms use GET for any possibly dangerous things. In fact, the only good use for GET forms I can think of is a search query, so that you can easily use it in the future by just changing the query in the URL.
Step 2 is quite critical. It’s difficult to protect forms against CSRF if there’s a script in the page which sends the CSRF key to the attacker.
Step 3 is the actual anti-CSRF measure. It’s quite simple, actually – create a key, store it in the session, and require it as a value in form submissions. If the form doesn’t contain the key generated on the previous request, it’s probably not a proper form submission.
A simple protection script
It’s relatively simple to protect a form against CSRF. We first need to generate a key, store it, and put it in the form. In the next request, the script needs to check whether the value was actually in the request or not..