Laravel 5.3 - TokenMismatchException in VerifyCsrf

2019-02-17 22:39发布

问题:

When I log in to my app, and immediately go back when I enter it, and then try to log out, I get the error from the title, how can I fix that?

回答1:

I was facing same issue with laravel 5.4 .. and then following command works for me :)

chmod 777 storage/framework/sessions/

before this, it was chmod 775 storage/framework/sessions/ ... hence I was facing the issue...

Happy coding



回答2:

From Laravel 5.3 docs

The Auth::routes method now registers a POST route for /logout instead of a GET route. This prevents other web applications from logging your users out of your application. To upgrade, you should either convert your logout requests to use the POST verb or register your own GET route for the /logout URI:

Option One: Route::get('/logout', 'Auth\LoginController@logout');

For more about upgrade please have a look at this https://laravel.com/docs/5.3/upgrade

Option 2

//Insert this on your head section
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

<!-- Scripts -->
<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

Where you want you logout

 <ul class="dropdown-menu" role="menu">
   <li>
       <a href="{{ url('/logout') }}" onclick="event.preventDefault();
            document.getElementById('logout-form').submit();"> Logout
         </a>

        <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
             {{ csrf_field() }}
         </form>
   </li>
</ul>

Cheers



回答3:

I solved this problem by editing the file config->session.php

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

and removing SESSION_DOMAIN from the file (.env)

and finally composer dumpautoload



回答4:

Actually i have the same issue in Laravel 5.4, when I upload a file using a form, I sent the token and the file uploads correctly. The issue appears when I upload a file that exceeds the max filesize upload. So, just add an exception in the VerifyCsrfToken.php for the route and the message disapears, but the file doesn't get upload.

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    protected $except = [

        'anexoSesion',
    ];
    public function handle($request, Closure $next)
    {
        return parent::handle($request, $next);
    }

}


回答5:

I faced this issue because I set 'secure' => env('SESSION_SECURE_COOKIE', false), to true for my localhost. The value is in the project-folder/config/session.php file. Since my localhost wasn't https that's why I was facing the issue. After making it false for my localhost the issue disappeared.



回答6:

I had the same problem. I run Laravel / PHP on a Windows machine with IIS. If you do as well, please make sure, the user IUSR have modify rights on the project directories. After permitting the user, the error was gone.



回答7:

This issue will generally occur due to permissions. As Manish noted you can chmod 777 on your sessions folder, however, I would not recommend this ever. First check if you have the same issue with the app using artisan serve (as opposed to serving your app via Nginx or Apache). If you don't then it is a permissions issue and you can change the ownership of the folder accordingly. Most likely it is the www-data user that needs permissions to write to the folder, however, you will want to check your environment to make sure as the user will differ in some cases.



回答8:

To solve this add those two lines in the route file (e.g web.php)

Route::get('/', 'HomeController@index');// so when you logged out it go back 
Route::get('/home', 'HomeController@index');

This solved the problem for me. Hope that help.



回答9:

Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php

use Closure; // import

protected $except = [
    //
];

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;
}

or


for all url

protected $except = [
    '*'
];

or


If there is no use

Illuminate\Foundation\Http\Kernel.php

// \App\Http\Middleware\VerifyCsrfToken::class

this line add comment



回答10:

I have added SESSION_DOMAIN=localhost in my .env file when my APP_URL is APP_URL=http://localhost. It works for me I use laravel 5.3



回答11:

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes

If you check your app/Providers/RouteServiceProvider.php, you will find that by default, a web middleware group is applied to all your routes in routes/web.php.

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

Now, if you go check your app/Http/Kernel.php and take a look at the $middlewareGroups property, you will find a new EncryptCookies middleware. You can read about it, but if you remove this middleware from the web middleware group, your app might not give the TokenMismatchException which you are getting currently.



回答12:

I am also facing this problem when using laravel5.4 for rest API. Just add the route name to the app/Http/Middleware/VerifyCsrfToken.php file.

protected $except = [

    'test/login',
];

After adding the line, then I run the API, it executes successfully.



回答13:

I faced this kind of problem in version 5.3.29 The following method worked for me.

Just change the following line in your .env file.

APP_KEY=base64:aBCdeFghI+jKLMnOPqRSTuvw1xYzAbCDeFgHiJKL57+4= (example key)

remove the base64: part, and make it like following

APP_KEY=aBCdeFghI+jKLMnOPqRSTuvw1xYzAbCDeFgHiJKL57+4=


回答14:

go to middleware -> verifycsrftoken.php -> add the urls in the array specified.



标签: laravel-5.3