Laravel 5.4 护照 axios 总是返回未认证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42030727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:15:39  来源:igfitidea点击:

Laravel 5.4 passport axios always returns Unauthenticated

laraveljwtlaravel-5.4laravel-passport

提问by Angad Dubey

I've followed the guide here:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript

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

Using axios:

使用 axios:

...
mounted: function() {

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

But the response is always unauthenticated, I check to see if a laravel_token cookie is present and it is:

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

enter image description here

在此处输入图片说明

I'm running on apache2 ( docker )

我在 apache2 ( docker ) 上运行

---- Update --

- - 更新 -

Upon debugging, its actually the xsrf token thats failing in this method in TokenGuard:

在调试时,它实际上是在此方法中失败的 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);
        }
    }

I have the appropriate setup in boostrap.js :

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

window.axios = require('axios');

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

回答by Michael

This is actually a Laravel / documentation issue.

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

The passport token guard is looking for X-CSRF-TOKEN, but axios sends X-XSRF-TOKEN. Change your axios configuration to:

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

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

I've opened an PRand this should be default in future Laravel versions.

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