Blog

Solved. Laravel 5. TokenMismatchException in VerifyCsrfToken

The TokenMismatchException in Laravel can be extremely tricky to solve and can take a fair amount of time.

Here is a quick step by step check list guide of how to solve the following exception throws in "TokenMismatchException in VerifyCsrfToken" in Laravel 5:

1. Check you have set a _token value csrf_field(), or csrf_token()  in the form you are sending.

2. Check you are actually sending the field

3. If using Ajax.

First. Set a meta field with the token.

 

Second. Then set it to be used globally:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
    }
});

4. If using XEditable you may first set it a meta field like the example above, then use like this:

var token = $('meta[name="csrf-token"]').attr('content');

$('#myaccount-name').editable({
    type: 'text',
    title: 'Enter new name',
    params: {_token:token},
});

3. Check your sessions are working. If not make sure your "storage" and "bootstrap/cache" directories are writable by the web user. You can use the script from here http://lesichkov.co.uk/article/20151113080209452243/laravel-fix

4. Check you are not sending more variables than the option "max_input_vars" set in your "php.ini" file. If so you have two options: increase the "max_input_vars" and restart the server, or decrease the form variables.

5. If you are using Ajax and it is ok from security point of view, you may want to disable CSRF for the specific route.

6. Check the server date time settings are correct and synchronized. Then check your Laravel config has the correct time zone.

7. Empty the Laravel sessions directory "/storage/framework/sessions" and cache. Then clear your browser cookies and cache, restart your browser. Check with a different broser.

8. Make sure your cookies are set to the root of the domain, and that the domain itseld is correct;

'path' => '/',

9. Very edge case described here: https://stackoverflow.com/questions/30490821/laravel-5-tokenmismatchexception-on-php-5-6-9/30508294#30508294

public function handle($request, Closure $next) { 
  $response = $next($request);

  if (last(explode('\\',get_class($response))) != 'RedirectResponse') {
    $response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
  }

  return $response;
}

The above check list should fix your issues with this "TokenMismatchException in VerifyCsrfToken" thrown in Laravel 5.

Thank you.