Laravel 5.4护照axios始终返回Unauthenticated

Ang*_*bey 4 jwt laravel laravel-passport laravel-5.4

我按照这里的指南: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);
                });
        },
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

我正在运行apache2(docker)

----更新 -

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

/**
     * 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};
Run Code Online (Sandbox Code Playgroud)

小智 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'
};
Run Code Online (Sandbox Code Playgroud)

我打开了一个公关,这在未来的Laravel版本中应该是默认的.