【问题标题】:Laravel 5.4 passport axios always returns UnauthenticatedLaravel 5.4 护照 axios 总是返回 Unauthenticated
【发布时间】:2017-06-21 04:58:36
【问题描述】:

我已按照此处的指南进行操作: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,它是:

我在 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'
};

【问题讨论】:

标签: laravel jwt laravel-5.4 laravel-passport


【解决方案1】:

这实际上是一个 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 版本中应该是默认的。

【讨论】:

  • window.Laravel.csrfToken 在哪里?
  • @user3098538 它应该在您的 /resources/views/layouts/app.blade.php 视图中,在 head 标签内。
猜你喜欢
  • 2019-06-15
  • 2019-11-24
  • 2020-04-19
  • 1970-01-01
  • 2018-05-15
  • 2016-04-01
  • 2017-12-10
  • 2018-11-03
  • 2020-11-29
相关资源
最近更新 更多