framework: TokenMismatchException in VerifyCsrfToken.php line 68:

  • Laravel Version: 5.3.19
  • PHP Version: 5.6.8
  • Database Driver & Version: 5.6.24 - MySQL Community Server (GPL)

Description: I am taking this very seriously. I’ve exhausted all other means of finding an answer, with google, laravel IRC, stack overflow, github (where this issue has come up but has been closed even though it’s not been resolved…?) and laracasts.

I’ve had a new laravel install since 5 days ago, Oct 18th 2016, and it’s been working perfectly. No issues, been building my app as needed. Everything working fine. Now, I’ve not added in any additions to the auth system, I ran php artisan make:auth and that was it, I was using the vanilla auth system as is because that’s all I needed. Here are my routes:

Auth::routes(); Route::resource(‘/posts’, ‘PostController’); Route::get(‘/admin’, ‘HomeController@getAdmin’); Route::get(‘/’, ‘HomeController@index’); Route::get(‘/blog’, ‘BlogController@getIndex’); Route::get(‘/blog/{slug}’, [‘as’ => ‘blog.single’, ‘uses’ => ‘BlogController@getSingle’])->where(‘slug’, ‘[\w\d-_]+’);

Here is the top of my views/auth/login.blade.php:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}"> {{ csrf_field() }}

Here is the <head> of my views/layouts/app.blade.php:

<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
    </script>

Here is my config/session.php:

‘driver’ => env(‘SESSION_DRIVER’, ‘file’), ‘lifetime’ => 120, ‘expire_on_close’ => false, ‘encrypt’ => false, ‘files’ => storage_path(‘framework/sessions’), ‘path’ => ‘/’, ‘domain’ => env(‘SESSION_DOMAIN’, ‘http://localhost’),

My .env file:

APP_ENV=local APP_KEY=base64:b/SdDNzT9sbREBnJgPDQ+YNTqJAJwLfgaKL4fmfnayk= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=mysite DB_USERNAME=root DB_PASSWORD=

BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file SESSION_DOMAIN=http://localhost QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379

MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

PUSHER_APP_ID= PUSHER_KEY= PUSHER_SECRET=

NOCAPTCHA_SECRET=[secret-key] NOCAPTCHA_SITEKEY=[site-key]

My Middleware/RedirectIfAuthenticated.php:

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/admin');
        }
        return $next($request);
    }

Which uses this function in my HomeController.php:

public function getAdmin()
    {
        return view('auth.home');
    }

As you can see matches the routes and views/auth/home.blade.php exists.

As I mentioned earlier, I have read the many stack overflow and laracast and github issues saying different things like include {{ csrf_token }} etc in the login forms, you can see I have that. I’ve tried solutions here, where more of the community have opened another thread about it because it was closed here on github: https://laracasts.com/discuss/channels/laravel/53-tokenmismatchexception-in-laravels-auth-form

I’ve went into vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php and dd()'d the tokens and they have shown this (most recent token):

2dwRDcyAoj4eGkXR0q9EH7yPcdmJXsn3c4OjaDI 2dwRDcyAoj4eGkXR0q9EH7yPcdmJXsn3c4OjaDI

They are matching! Yet, Laravel is throwing this issue. So I cleared my browser cache and deleted all the /storage/framework/session and view files because I have many laravel installs on this PC because I LOVE Laravel, I want to use it for everything but this is a serious issue and I feel kind of bummed that it’s being swept under the rug when many people are complaining about it. It’s the first time I’ve experienced this with Laravel, I’ve always found solutions to my problems but now it feels like this isn’t being acknowledged and this is really a gamebreaker when I need to make sure this won’t happen to a client while they’re trying to login.

So I tried some other ways to figure out what might be causing this error in my middleware/VerifyCsrfToken.php as below:

public function handle($request, Closure $next)
    {
        if($request->input('_token')) {
            if ( \Session::getToken() != $request->input('_token')) {
                   dd(\Session::getToken() == $request->input('_token'));
                \Log::error("Expired token found. Redirecting to /");
                return redirect()->guest('/');
            }
        }

        return parent::handle($request, $next);
    }

KpsW5855ieQxBA32rKdhqTpby1l53dRKmkduN0iw vzQ9RNeQ56VPAMGhN9T2P97AdDGp5BXKquvKmRrQ

AH HA!

The tokens are not matching here suddenly! They are matching all the way down in the src/ but up here something is happening to cause the Session and view token to misalign. Why?? Please help Taylor. I just want to get this fixed so I can go back to making awesome things.

I know the rest of the community wants to know too, I don’t want to go back to Laravel 5.2 I like 5.3.

Please offer a fix!

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 66 (6 by maintainers)

Most upvoted comments

@themsaid dude, please don’t come here and close my issue when I spent all that time typing out and CLEARLY showing my configuration which is configured properly and NO packages installed. Just because you “never had this problem” has nothing to do with others including myself, having this problem. Do you understand what a bug is? I have over 35 laravel apps running on this machine. All are 5.2 and below. The one 5.3 app I have running has this issue.

This is how projects end up sucking. When people like you want to close the issue so fast you don’t take the time to understand the problem or why it’s happening. I like using Laravel too much to have little peeons like you come and just casually say “maybe a package that has side effects” if you took the 2 seconds to read my post you’ll see I HAVE NO PACKAGES installed.

Additionally, I’m clearly not the only person having this issue. It’s not a one off it’s a serious problem affecting multiple users and is continuously being swept under the rug because you don’t know wtf you’re doing so you Close it because “I have many apps running and never had this problem” I don’t give a fuck what you have running. I’ve shown my configuration and I’ve shown the issue how about you try to fucking fix it before closing the issue?

Re-open this until it’s been fixed. Or better yet why don’t you step down because it’s clear you dont’ deserve to be a member of the framework.

Well I have many apps running on laravel and never had this problem 😃 It’s really a matter of improper configuration or maybe a package that has side effects.

Anyway feel free to ping me if you ever had this issue in the future.

Comment the \App\Http\Middleware\VerifyCsrfToken::class line from App\Http\Kernel.php. It will disable the csrfToken check in the session.

It worked for me.

@astr0naugh7 , please check for spaces in your routes/web.php file. i had the same problem and a space before the opening tag <?php caused the earthquake 😃

I solved this problem. I edited this file config->session.php

'domain' => env('SESSION_DOMAIN', null),

Remove SESSION_DOMAIN from the file (.env)

and composer dumpautoload

@astr0naugh7

I had the same/similiar issue after i changed group ownership of the cache/session storage folders from apache to a custom group (then adding apache user to that custom group).

Was drivin me nuts for about an hour before I remembered to restart apache (duh) and clear the existing cache and sessions.

sudo rm -rf storage/framework/sessions/* sudo php artisan cache:clear

Tada! Working again.

Not sure if this is your problem or not, but I’d wager you may be in the same boat as I was especially if you’re just using a stock install with make:auth.

-voxx

I’ve been testing on a new install and I copied over all my files and it’s working

Clearly something happened in your application down the road that lead to this behaviour, it’s really hard to fix something we can’t replicate, if on a fresh installation using the same config the issue doesn’t show up that means we have something missing and it’ll be really hard to figure out what’s wrong in such situation.

It’s been a while now since the issue is closed, please let me know if you ever found out what lead to this situation.

I just have the same problem, and finally I found the answer ! So simple, just add this {!! csrf_field() !!} on your form. It worked for me 👍

Everytime this is reported it ends up with a misconfiguration, and it’s really hard to debug from where everything is working fine so I suggest that you install a fresh 5.3 instance, run php artisan make:auth and then try the login/register form.

@devcircus Sure, I understand the point you make. I have been working for major global software suppliers since 1985, and I agree, in many cases, you are correct. However, for every developer who goes to the effort of leaving a message here there are 20 more who have not bothered.

We all know developing s/w is hard, no less so for those who build frameworks. Be careful not to fall into the “Microsoft trap” of “it works over here, so it must be your config” . As much as this might be true, over the long run, this approach will only damage the reputation of Laravel. And so, as hard as it is to solve this problem (and others) some real heavy lifting must be invested to protect the user and most importantly Laravel from this kind of problem. As Laravel becomes more and more complex, this kind of problem will only multiply.

Never forget the developer makes use of Frameworks to make his life easier, not harder. If the developer has to spend more time understanding and unravelling the mysteries and complexities of a Framework then it defeats its purpose. I sense we are fast approaching that tipping point with L5.4. I am in the midst of upgrading from 5.1 to 5.4. So far it has been nothing but problems, errors, hours of reading literature. 5.1 was easy to understand. You knew where everything was and what it was doing. 5.4 appears to have a mind of it’s own, dynamically inventing it’s routes, files and class entries. Half the time you don’t know what is going on nor why. Add more features and with it more complexity, but at the very, very minimum, the documentation must be much, much more thorough. Laravel should not rely upon Stack Overflow to solve it’s user problems. Better still, add software protections to alert users to problems AND solutions.

So, In conclusion, do not fall into the trap of delivering ever more features when the features you have can not and are not being effectively used by the developer community, for there in lies the “death by Microsoft”. Thanks for reading this much. Cheers !

In my case, this was down to using a non-secure connection with SESSION_SECURE_COOKIE set to true. Might be worth checking if you’re also having this issue.

@antoniogocaj out of every comment here, your solution worked for me, there were a couple of empty lines before the start of my <?php in my routes file, after I removed them the tokens stopped mismatching. I just sat there saying “what the fuck…” for the next two minutes. HOW ON EARTH DO EMPTY SPACES IN A ROUTES FILE CAUSE THIS? PLEASE LOOK INTO THIS LARAVEL DEVS!!!

Try it it will solve your problem, It is because of http and https conflict. Goto “session.php” file change this: ‘secure’ => env(‘SESSION_SECURE_COOKIE’, false), to this: ‘secure’ => true,

in laravel 5.5 solved !

when i use php artisan serve and use site at 127.0.0.1:8000 everything works fine but when is custom domain there is token error

Setting the permissions above worked for me!

sudo chmod - R o+w storage

sudo chmod -R o+w storage

Please take care of {{csrf_field ()}} is inside the login form

<form class = "form-signin" method = "POST" action = "{{route ('login')}}"> {{csrf_field ()}}

This helped me.

I am been working in node/express for years now and started helping a friend with a Laravel project cause it need some extra love.

This entire thread is wild. Why can’t some tests be written to fix this and pinpoint a fix more easily? There are like 15 answers on a fix above and they are all drastically different.

I had a similar problem and it turns out that my problem was in the file Kernel.php

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

These two lines: \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, Were also included in:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
          //  \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
           // \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
]

Since the first declaration already applies all Middlewares to every request i guess they are not needed in the WEB group i commented them out. Including them two times was probably causing some sort of conflict and i left them global because my login route isn’t part of the WEB group.

I hope i explained my problem clearly enough and that it helps you solving yours.

Hello, my solutions is the next:

public function handle($request, Closure $next)
    {
        if (
            parent::isReading($request) ||
            parent::runningUnitTests() ||
            parent::shouldPassThrough($request) ||
            parent::tokensMatch($request)
        ) {
            return parent::addCookieToResponse($request, $next($request));
        }

        return back()->with('error','The token has expired, please try again.');
    }

Insert this code in app/Http/Middleware/VerifyCsrfToken.php is’t a a override of the method de class parent.

Regarts

I have the same problem. It’s not good enough to just say, “it’s your config, we’re just fine”. If it might be that then you need to make an effort to alert the user to the problem. There are just too many incidents occurring to be brushed off as user error. Laravel has to be bullet proof. Please take this seriously.