Laravel 5.1 中 VerifyCsrfToken.php 第 53 行中的 TokenMismatchException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30934906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:08:30  来源:igfitidea点击:

TokenMismatchException in VerifyCsrfToken.php line 53 in Laravel 5.1

phpsessionlaravel-5session-cookiescsrf

提问by reza_khalafi

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.phpit makes me login but after Redirect to my dashboard I'm not logged in. I am using MAMP on mac.

当我尝试登录时显示令牌错误。我在视图中检查了令牌是正确的,当评论时\App\Http\Middleware\VerifyCsrfToken::classKernel.php它让我登录,但在重定向到我的仪表板后我没有登录。我在 mac 上使用 MAMP。

<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 Packagefor login.

同时我Sentry Package用于登录。

    /**
     * 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!!!!!']);
         }
}

采纳答案by Emeka Mbah

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()

由于您使用的是表单构建器,因此请从表单中删除它。当您这样做时,Laravel 表单构建器会自动向您的表单添加一个隐藏的令牌字段Form::open()

So remove this line:

所以删除这一行:

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

回答by Honest Knight

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

好吧,我认为所有人都在注销时错过了 CSRF 令牌创建!

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

如果您使用{!!Form::open()!!}它,它将自动创建令牌。否则你可以使用

<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!

只是立即形式打开。最重要的是使用return Redirect::to('');控制器功能或页面重新加载或 ajax 重新加载可以创建令牌!

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!

我认为它可能会解决问题,因为它对我有用!

回答by Gabriel Sigouin

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.

全新安装 Laravel 5.1,没有从 5.0 版到 5.1 版的 Composer 更新,我看到了一些差异,一个在 Middleware 文件夹中。

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

EncryptCookies.php 是一个新的中间件,看看你有没有。

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.

所以,我没有再次测试,我现在将我的文件从 5.0 版转移到 5.1 版的新安装,但我很确定这可以解决这个问题,EncryptCookies.php 在堆栈中令牌不匹配错误。

回答by Fokwa Best

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

添加{!! csrf_field() !!}解决了我的问题,如下所示:

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

</form>

If using Laravel Form helper such as below:

如果使用 Laravel 表单助手,如下所示:

{!! 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.

CSRF 代码将自动添加到您的 html 脚本中。还要确保在浏览器中查看源代码以确保确实添加了如下所示的字段。

<input type="hidden" name="_token" value="dHWBudjTyha9AMr0SuV2ABq5NNK6bTIDZDXRWCBA">

回答by majid

I have same problem while using this code

使用此代码时我遇到了同样的问题

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

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

by changing it to {!! csrf_field() !!}solve my problem

通过改变它来{!! csrf_field() !!}解决我的问题

i'm on L5.1

我在 L5.1

回答by Mamun Rasid

It works for me.

这个对我有用。

<meta name="csrf-token" content="{{ csrf_token() }}" />

<script>
function getMessage(){ 
$.ajax({
   headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
   type:'POST',
   url:'/getmsg',
   // data:'_token = <?php echo csrf_token() ?>',
   success:function(data){
      $("#msg").html(data.msg);
   }
 });
}
</script>

{{ Form::button('Replace Message',['onClick'=>'getMessage()']) }}

回答by Dennis Koster

I was also having this problem when trying to upload a file. Turned out the max_post_size was being exceeded, in which case apparently all POST variables are cleared and therefore no token is being received.

我在尝试上传文件时也遇到了这个问题。结果发现超出了 max_post_size,在这种情况下,显然所有 POST 变量都被清除,因此没有收到令牌。

回答by Siddharth Jogia

You did not post your sample code in your question.

您没有在问题中发布示例代码。

Therefore check your code with the following options,

因此,请使用以下选项检查您的代码,

try with hidden input field value:

尝试使用隐藏的输入字段值:

{!! csrf_token() !!} or {{ csrf_token() }}

You can also use form blade template:

您还可以使用表单刀片模板:

{!! Form::open(array('method' => 'GET/POST','url' => 'YOUR_URL',)) !!}

This will automatically add CSRF Code in your html script

这将自动在您的 html 脚本中添加 CSRF 代码

One more thing to include in <head>section is:

<head>部分要包括的另一件事是:

<meta name="csrf-token" content="{{ csrf_token() }}">

回答by IshaS

Add <?php echo Form::token(); ?>in side the form.

<?php echo Form::token(); ?>在表格旁边添加。

回答by Mario Ene

This solution worked for me:

这个解决方案对我有用:

Add {{ csrf_field() }}anywhere in the form.

{{ csrf_field() }}在表单中的任意位置添加。