带有Vuejs的Laravel 7.x Sanctum(SPA)始终返回401未经授权

时间:2020-06-13 02:20:41

标签: php laravel vue.js single-page-application laravel-sanctum

这已经有几个小时了,我什至无法通读并尝试互联网上可用的任何解决方案,也无法弄清这个问题。我正在将 Laravel 7.x Vue js 结合使用,并且在 Sanctum SPA 身份验证中苦苦挣扎。

使用 web.php

中定义的 Auth :: routes()

登录请求可以正常工作

enter image description here

但是,对在 auth:sanctum中间件下的 api.php 中定义的API的任何请求均返回401。例如,调用获取用户对象失败,状态为401:

enter image description here

这是请求标头:

enter image description here

这是 web.php

enter image description here

这是 api.php

enter image description here

这是 sanctum.php

中的有状态对象

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000')),

在vue.js方面,我已将withCredentials标志设置为true:

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

window.axios.defaults.withCredentials = true;

cors.php 中,suports_credentials标志也设置为true

enter image description here

,这是我的 Kernel.php

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

2 个答案:

答案 0 :(得分:5)

我遇到了同样的问题,但找不到任何答案,但在进行故障排除后,它开始工作了。

您的问题是您正在通过localhost端口8000访问它,但是在Sanctum配置下的有状态参数中没有localhost:8000(甚至localhost都指向{{1} })。该配置使用127.0.0.1,因此在访问它时实际上会查找确切的内容。

下面的简单修复方法:

$_SERVER['SERVER_NAME']

答案 1 :(得分:-1)

我不使用Sanctum,而是使用Vuejs Laravel和Axios,我注意到您需要在所有axios受保护的URL中添加标头授权

承载您的令牌

我在ap.js上使用

import jwtToken from './helpers/jwt-token'

    axios.interceptors.request.use(config => {
        config.headers['X-CSRF-TOKEN'] = window.Laravel.csrfToken
        config.headers['X-Requested-With'] = 'XMLHttpRequest'

        if (jwtToken.getToken()) {
            config.headers['Authorization'] = 'Bearer ' + jwtToken.getToken()
        }

        return config;
    }, error => {
        return Promise.reject(error);
    });

和我的JWTTOKEN js文件

export default {
    setToken(token) {
        window.localStorage.setItem('jwt_token', token);
    },
    getToken() {
        return window.localStorage.getItem('jwt_token');
    },
}

因此axios的所有请求都发送带有Bearer +令牌的Authorization标头

希望对您有帮助