首页 文章

CSRF令牌不匹配错误,Laravel 5.3 / VueJS2

提问于
浏览
0

我正在尝试获取我正在构建的应用程序的Auth部分 . 我使用Laravel 5.3和VueJs 2作为我的JS框架 . 在我的登录组件中,我有类似的东西 .

<template>
    <form @submit="test" method="POST" action="/test">
        <input v-model='input' type='text'>
        <button type='submit'>Submit</button>
    </form>
</template>

<script>
    export default {
        data() {
            return {
                data: {
                    input: "hello"
                }
            }
        },
        mounted() {
            console.log('Component ready.')
        },
        methods: {
            test: function() {
                this.$http.post('/test', {
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name=_token]').attr('content')
                    }
                })
                .then(res => {
                    console.log(res);
                })
                .catch(err => {
                    console.error(err);
                });
            }
        }
    }
</script>

我还将CSRF令牌设置为HTML文档头部的元数据 . <meta name="_token" content="{{ csrf_token() }}">

Laravel 5.3 's Illuminate\Foundation\Http\Middleware\VerifyCsrfToken spits the error out, saying there is a token mismatch. I' m当前var_dumping输出到此类' handle() 函数的所有$ request信息 .

public function handle($request, Closure $next)
    {
        var_dump($request);
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }
        throw new TokenMismatchException;
    }

我不发送.2508883_发送 . 's odd is that if I don' t使用ajax并在表单标签内执行正常的表单提交,例如 {{csrf_field()}} ,中间件成功验证令牌 . 这让我相信这是ajax / vue-resource的一个问题,我已经搜索了关于这个问题的google posts / stackoverflow / youtube视频,但没有's fixed the error. I'已经做了一个解决方法,我强制将XSRF-TOKEN cookie与令牌,但这让我想到安全问题以及当用户在使用应用程序时意外或不知不觉地删除了Cookie时会发生什么 . 不确定这是否会导致错误,但我已经与其他开发人员/工程师交谈,他们说强制在中间件而不是CSRF_TOKEN中比较cookie并不是一个好主意 .

以下是我尝试过的其他一些事情 .

//I've tried the vue.http.interceptors method that comes with the bootstrap.js file Laravel generates for vue js 2.
Vue.http.interceptors() //something along those lines
//Setting ajax setup in bootstrap.js as wel

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
});

//I've also tried sending the token along with the vue-resource post request in the Vue component method as well.

methods: {
  test: function() {
    this.$http.post('/test', {headers: 'X-CSRF-TOKEN: $('meta[name='_token']'.attr('content')}
    ).then(response => console.log(response));
  }
}

//I've also tried using axios as my http client as well.

对于为什么会出现这种情况以及如何解决这个问题的任何建议或见解?

1 回答

  • 0

    我会安装Laravel Passport(https://laravel.com/docs/5.3/passport

    这实际上增加了通过前端Vue进行身份验证所需的一切 .

    它还为您的应用添加了oAuth支持,这意味着用户可以生成API密钥并使用他们自己的客户端来使用您的API(如果您想这样做) .

相关问题