How to resolve TokenMismatchException in Laravel 5

2019-05-27 15:26发布

I have developed a laravel 5 app and everything works fine except that I occationally get TokenMismatchException in VerifyCsrfToken.php line 53. I can't seem to figure out the cause. This happens mostly during login. I used the laravel built-in trait to implement authentication. Below is my sample logout method.

public function getLogout()
    {
        Auth::logout();
        Session::forget('cart_id');
        Session::forget('is_supervisor');
        Session::forget('is_manager');
        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

Each time the exception occurs, I have to reload the page and login again before this works. Below is a sample of my login form:

{!! Form::open(array('class' => 'form-horizontal', 'role' => 'form')) !!}
     <div class="form-group">
         {!! Form::label('username', trans('home.username'), array('class' => 'col-sm-3 control-label')) !!}
             <div class="col-sm-9 col-lg-5">
                {!! Form::text('username', null, array('required' => 'required', 'class' => 'form-control input-sm')) !!}
                        </div>
          </div>
{!! Form::close() !!}

When I check the page source, the csrf token is always available. What could possibly be the problem. I am using laravel 5.1.* and SESSION_DRIVER=file in .env.

Edit

// Authentication routes...

Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

标签: laravel-5.1
1条回答
Anthone
2楼-- · 2019-05-27 15:51

CSRF Protection (Cross-Site-Request-Forgery) saves you from unwanted actions on web application. The token is generated when rendering form and expired after some time. If you have the form opened too long, you get TokenMismatchException.

Did you notice the problem shortly after reload page (form)?

Try to add {{ csrf_field() }} to your form and check if it helps.

查看更多
登录 后发表回答