I'm using Symfony 3.1 with FOS user bundle.
I get a "CSRF invalid token" message for the login form the first time I logged in (in incognito mode)
I noticed that in the 1st request, I get a token. Then I refresh the page and get another one. From then on, I get the same token (and works correctly). For example:
1st request: maJl7bBRR0iuOX4A96cOxrsLdklBIxz3mCP7fSMGqQY
2nd request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8
3rd request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8
4th request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8
I tested twice resulting in the same behavior.
It doesn't seem to be a browser cache problem because of the header:
Cache-Control:no-cache
The csrf input in the form is generated like this:
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
After it fails the first time, everything goes ok (the 2nd csrf token works properly)
I want to don't fail validation the first time I login because of the CSRF token, which I suspect is failing because of what I mentioned above. Removing CSRF protection is not a solution.
Thanks!
UPDATE
I found the problem but not the solution. The project stores the session data in MySQL. The first time it access it doesn't insert the data in the database, but the second it does. The data is present in $_SESSION, but as it's not stored in MySQL the first time, the csrf token is lost.(I found this logging the queries made from the app thanks to this How to show the last queries executed on MySQL?).
Storing the session in files works fine. This is not a solution because there are going to be multiple instances of the app in different servers.