Laravel 5.4护照axios始终返回Unauthenticated

时间:2017-02-03 18:27:15

标签: laravel jwt laravel-5.4 laravel-passport

我已按照指南进行操作:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript

使用axios:

...
mounted: function() {

            axios.get('/api/user')
                .then(function (response) {
                    console.log(response)
                })
                .catch(function (response) {
                    console.error(response);
                });
        },

但是响应始终是未经身份验证的,我检查是否存在laravel_token cookie并且它是:

enter image description here

我在apache2(docker)上运行

----更新 -

调试时,它实际上是TokenGuard中此方法失败的xsrf标记:

/**
     * Authenticate the incoming request via the token cookie.
     *
     * @param  Request  $request
     * @return mixed
     */
    protected function authenticateViaCookie($request)
    {

        try {
            $token = $this->decodeJwtTokenCookie($request);
        } catch (Exception $e) {
            return;
        }

        # This is not passing:
        if (! $this->validCsrf($token, $request) ||
            time() >= $token['expiry']) {
            return;
        }


        if ($user = $this->provider->retrieveById($token['sub'])) {
            return $user->withAccessToken(new TransientToken);
        }
    }

我在boostrap.js中有适当的设置:

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

1 个答案:

答案 0 :(得分:11)

这实际上是一个Laravel /文档问题。

护照令牌警卫正在寻找X-CSRF-TOKEN,但是axios发送X-XSRF-TOKEN。将您的axios配置更改为:

window.axios.defaults.headers.common = {
  'X-CSRF-TOKEN': window.Laravel.csrfToken,
  'X-Requested-With': 'XMLHttpRequest'
};

我已经打开PR,这在未来的Laravel版本中应该是默认的。