Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stigaard's avatar

TokenMismatchException in 5.0

Hey artisans,

I've created a 5.0 project and created my first form, however, when the middleware verifying the CSRF token i get a exception EVERY TIME. Others have also experienced the problem, however, no solution is found yet. Can you please help? More details about the problem is posted here: http://laravel.io/forum/01-30-2015-laravel5-tokenmismatchexception-in-verifycsrftoken

EDIT: Some details of mine: Setting up laravel using cookies as session driver. I use Windows 8, however, my collegue using OS X running the project does NOT experience this problem!

0 likes
4 replies
bestmomo's avatar

Hey !

I use Windows 8 and all works fine, no matter which OS is used.

First make sure you have Mcrypt PHP Extension.

Laravel just check if token match so you should debug in Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php in tokensMatch method :

/**
 * Determine if the session and input CSRF tokens match.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function tokensMatch($request)
{
    $token = $request->session()->token();

    $header = $request->header('X-XSRF-TOKEN');

    return StringUtils::equals($token, $request->input('_token')) ||
           ($header && StringUtils::equals($token, $this->encrypter->decrypt($header)));
}

Hope this helps.

stigaard's avatar

phpinfo() shows that mcrypt is enabled, however, in my config file app.php, the crypt algorithm is defined:

'cipher' => MCRYPT_RIJNDAEL_128,

The algorithm seems supported (in phpinfo()):

Supported ciphers:  cast-128 gost rijndael-128 twofish cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish enigma rc2 tripledes arcfour
rapliandras's avatar

If using AJAX requests, make sure, that you set the correct header

$header = $request->header('X-CSRF-TOKEN');

and

$header = $request->header('X-XSRF-TOKEN');

are not the same. Most tutorials mention CSRF-token, but it's actually XSRF written in the base verifier. Also make sure, that the encryption is correct and all values are set.

<meta name="_token" content="{{ app('Illuminate\Encryption\Encrypter')->encrypt(csrf_token()) }}" />
<script>
$(function() {
    $.ajaxSetup({
        headers: {
            'X-XSRF-Token': $('meta[name="_token"]').attr('content')
        }
    });
});
</script>

If using this solution, no modification is needed in your middleware.

2 likes
sid's avatar

@rapliandras: I was stuck with the same issue and your answer was exactly what solved the issue. I spent the better part of a day digging through the whole stack and turns out all I needed was this single post. Many thanks! I owe you a beer!

Please or to participate in this conversation.