TokenMismatchException in VerifyCsrfToken.php line 53 in Laravel 5.1

28,792

Solution 1

Edited:

Since you are using Form builder remove this from your form. Laravel form builder automatically adds a hidden token field to your form when you do Form::open()

So remove this line:

 <input type="hidden" name="_token" value="{{ csrf_token() }}">

Solution 2

Well I think all missed the CSRF Token creation while logout!

As I have solved out the problem.

Just add below code to the header.

<meta name="csrf-token" content="{{ csrf_token() }}">
<script type=text/javascript>
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
    });
 </script>

And if you use {!!Form::open()!!} it will automatically create the token. Otherwise you can use

<input type="hidden" name="_token" id="_token" value="{!! $csrf_token !!}}" />

or

{!! csrf_field() !!}

just immediate form open. Most importantly use return Redirect::to(''); on controller function or a page reload or ajax reload that the token can be created!

Like:

public function logout() {
    Session::flush();
    Auth::logout();

    return Redirect::to('/');
}

For ensure the token properly created or not check "view page source" on browser and it will shows like:

<meta name="csrf-token" content="TbgWTQZhTv0J4eFBQNU4rlM3jOlmBeYlTgf0waZB">
    <script type=text/javascript>
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
    });
    </script>


<form method="POST" action="/login-process" accept-charset="UTF-8" class="form-inline"><input name="_token" type="hidden" value="TbgWTQZhTv0J4eFBQNU4rlM3jOlmBeYlTgf0waZB">   

I think it might solve the problem as it worked for me!

Solution 3

With a fresh install of Laravel 5.1, without just a composer update from version 5.0 to 5.1 I see some differences and one in the Middleware folder.

EncryptCookies.php are a new Middleware, check if you have it.

So, I don't have tested again, I tranfert at the moment my files from my version 5.0 to a new installation of version 5.1 but im pretty sure that can be the solution for this problem, EncryptCookies.php was in the stack of the token mismatch error.

Solution 4

Adding {!! csrf_field() !!} solved my problem as shown below:

<form action="#" method="post" class="form-horizontal" role="form">
{!! csrf_field() !!}

</form>

If using Laravel Form helper such as below:

{!! Form::open(array('class' => 'form-horizontal', 'role' => 'form')) !!}

CSRF Code will be added automatically in your html script. Also make sure to view the source code in browser to be certain that a field such as below was indeed added.

<input type="hidden" name="_token" value="dHWBudjTyha9AMr0SuV2ABq5NNK6bTIDZDXRWCBA">
Share:
28,792
reza_khalafi
Author by

reza_khalafi

PHP,iOS,Android developer Laravel framework. Objective-C. Swift. Java. Kotlin. From IRAN

Updated on December 27, 2020

Comments

  • reza_khalafi
    reza_khalafi over 3 years

    When I try to login show me token error. I have checked token in view form it's right and when comment \App\Http\Middleware\VerifyCsrfToken::class, in the Kernel.php it makes me login but after Redirect to my dashboard I'm not logged in. I am using MAMP on mac.

    <div>
        <h1>Login</h1>
        <div>
            {!! Form::open(['url'=>'user/login','class' => '']) !!}
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <ul>
              <li><label>Customer Code</label>{!!Form::Text('customer_code',Input::old('customer_code'),['class'=>''])!!}</li>
              <li><label>Password</label>{!!Form::Password('password','',['class'=>''])!!}</li>
              <li>{!! Form::submit('Submit',array('class' => 'btn')) !!}</li>
            </ul> 
            {!!Form::close()!!}
        </div>
        <div><a href="{!!URL::to('user/forget_password')!!}">Forget Password</a></div>
    </div>
    

    Meanwhile I use Sentry Package for login.

        /**
         * post_login
         */
        public function post_login()
        { 
            try
            {
                $rules  = [ 
                        'customer_code'         => 'required',
                        'password'              => 'required',
                    ] ;                    
                $message = [ 
                        'customer_code.required'             => 'erorrr1',
                        'password.required'                =>'error2'    
                                 ];                            
                $validator = Validator::make(Input::all(), $rules,$message);
                if ($validator->fails())
                {            
                    return Redirect::back()->withErrors($validator)->withInput();        
                } // if ($validator->fails())
                else
                {
                $authUser = Sentry::authenticateAndRemember(array(
                                          'customer_code'    => Input::get('customer_code'),
                                          'password' => Input::get('password')), false);
    
                               if($authUser) 
                               {
                                    //$login = Sentry::loginAndRemember($authUser);
                                     return Redirect::to('user/panel/'.$authUser->id)->with('comment', 'Welcome');
                               }
                               else
                               {
                                 return Redirect::back()->with('comment', 'Error for login');
                               }
                }//validator                           
            }
             catch(\Exception $e)
             {
                 return Redirect::back()->withInput(Input::except('password','file'))->withErrors(['ERROR!!!!!']);
             }
    }
    
  • reza_khalafi
    reza_khalafi almost 9 years
    i used this script already but does not worked. i have token in my form.
  • Siddharth Jogia
    Siddharth Jogia almost 9 years
    Remove CSRF hidden field, as you have used Form::open() CSRF will be automatically added. You also need to change your controller method name to "postLogin".
  • Emeka Mbah
    Emeka Mbah almost 9 years
    After you edited your question I notice you are adding to token fields. Please check my edited answer
  • Memonic
    Memonic over 8 years
    If anyone wants to except some routes from "authing" then i suggestion going to app/Http/Middleware/VerifyCrsfToken.php and add protected $except = [ 'route_1', 'route_1/*', ];
  • ρяσѕρєя K
    ρяσѕρєя K over 8 years
    This should be a comment