Thursday, April 17, 2014

Laravel 4: CSRF TokenMismatchException when using stored form values

Problem: 
One of my client's Laravel web sites was having issues with logging in users where the first time, they would get the TokenMismatchException (gracefully handled, of course) and then they could log in as expected.

Solution:
My first thought was that for some reason the browser was storing the _token value along with their login credentials, so I wanted to force Laravel to regenerate the CSRF token and use one that had not already expired. While I could find no easy handle to regenerate the CSRF token, I did find that I could regenerate the session ID which would ultimately cause the same result.

Session::regenerate();

Note: This problem only existed when users were not logged in, otherwise regenerating the session ID might have interrupted their session.