帮助中心 >  技术知识库 >  网站相关 >  程序开发 >  Laravel 5 出现错误 TokenMismatchException in VerifyCsrfToken.php

Laravel 5 出现错误 TokenMismatchException in VerifyCsrfToken.php

2019-04-08 10:04:10 9422

进行 post 或 put 等方法提交表单的时候,laravel 会提示错误TokenMismatchException 这是因为laravel开启了防csrf。要解决该问题有两种方式,一种是在表单中填写token验证,另一种是在防CSRF时排除所请求的路由


开启csrf_token

在表单中加上laravel自带的全局帮助函数csrf_token()。提交表单的时候会自动带上laravel生成的csrf_token()的值,然后在访问路由的时候laravel会判断这个值。


<form action="/posts" method="post">

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

    <input type="submit" name="提交" />

</form>

或者使用


<form action="/posts" method="post">

    {{csrf_field()}}

    <input type="submit" name="提交" />

</form>

如果使用 ajax 提交的话


<head>

    <title>Laravel 5</title>

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

</head>

<script>

$.ajax({

    headers: {

        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 

    }, 

    url: "{{url('/rsa_post')}}",

    type: "post", 

    dataType: "json",

    data: {key: 'value'},

    success: function(data){

    }

}, 'json');

</script>

排除csrf保护url

比如要访问的url为 http://www.landui.com/posts 现在想排除 posts 相关资源路由,则在App\\Http\\Middleware\\VerifyCsrfToken::class 中添加路由如下:


protected $except = [

    'posts',

    'posts/*'

];

注意方法二将无法对photo相关路由进行CSRF防护,所以请根据实际情况选择


关闭csrf保护

当我们不想启用框架自带的csrf防护的时候,进入:laravel/app/Middleware/VerifyCsrfToken.php 找到csrf的中间件,修改代码如下


public function handle($request, Closure $next){

    // 使用CSRF

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

    // 禁用CSRF

    //return $next($request);

}

有的时候我们既需要开启CSRF防护,又需要在一些特性的post请求时不带csrf_token(),laravel框架为我们提供了一个特殊的属性。


class VerifyCsrfToken extends BaseVerifier {

    /**

     * The URIs that should be excluded from CSRF verification.

     *

     * @var array

     */

    protected $except = [ // 'upload', 'rsa_post', ];

    /*  public function handle($request, Closure $next)

    {

        // 使用CSRF

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

        // 禁用CSRF

        //return $next($request);

    }*/

}

这段代码的意思是利用except来进行路由过滤。在我们except中的是我们不想被防护的路由名称。此处的upload和rsa_post,都是我需要post方式访问的路由。


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: