In a nutshell a CSRF attack works when a user has been authenticated against a website and receives say a malicious link that once clicked makes the user perform a state changing operation on the website without their knowledge (like in the case of the image above).
A way to mitigate against such types of attacks specifically for web based form submissions is by introducing a token that is generated by the website and linked with the user and the form that they are trying to submit. If the token is not there or if it has expired the user is asked to retry or refresh their web page and try again.
The CSRF tokens come as part of the Form component and you can even generate them yourself if you use a custom form. They rely on a session being present as that’s where they are stored and if you load a form that uses CSRF protection a session will automatically get started for the current user. You can find more information about the CSRF protection in Symfony on the official documentation.
Personally I run into a very weird bug in one of my sites the other day and it took me a while to understand what was happening (all tied with the CSRF checks on a login form). The dreaded Symfony error was
The CSRF token is invalid. Please try to resubmit the form
I was sure that I had done no changes to the code, no upgrade of whatever nature that could have caused my forms to stop working like that. Interestingly the reason why I was getting that error was due to a setting that I had changed in the site’s configuration and my changing of the development environment (I was setting up a new box).
My site was using the following:
Which actually means that the cookie for the site would only be set if the site was being accessed via https. On my development environment I was not yet using https which means that the framework could not set the session cookie which means that it could not correctly verify the CSRF token on the login form and hence the error 💡.
Changing the local environment to always use https resolved this issue 🎆!