Laravel 中基于 Vue cookie 的身份验证

时间:2021-02-23 17:17:16

标签: laravel vue.js authentication laravel-sanctum laravel-breeze

从阅读 Laravel 文档来看,似乎在使用 Sanctum Vue 时只会使用基于 cookie 的身份验证。

我试图将现有应用程序(使用 Livewire 完成登录)移动到 Vue,但直接调用我的第一个 api 端点被重定向到登录页面。

所以我创建了一个全新的 Larvel 安装,安装了 Breeze(带有 Inertia),然后是 Sanctum,发布了配置等。

但是当我登录然后访问我的测试端点(它只返回 200 Ok)时,它会重定向到登录页面(因为我已登录,所以重定向到 Breeze 仪表板)。

我是否需要为由 auth:sanctum 保护的端点手动执行任何操作以通过身份验证?

更新

我设置了 axios.defaults.withCredentials,它返回 401 Unauthorized。我的 app.js:

axios.defaults.withCredentials = true;
axios.get('/api/test')
    .then(function (response) {
        // handle success
        console.log(response);
    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })
    .then(function () {
        // always executed
    });

1 个答案:

答案 0 :(得分:0)

首先确保您的应用程序的 CORS 配置返回值为 Access-Control-Allow-CredentialsTrue 标头。这可以通过将应用程序的 supports_credentials 配置文件中的 config/cors.php 选项设置为 true 来实现。

然后,如果您使用的是 axios,您应该在您的 axios 实例上启用 withCredentials 选项:

axios.get('some api url', {withCredentials: true});

或全局:

axios.defaults.withCredentials = true;

如果您不使用 Axios 从前端发出 HTTP 请求,则应在自己的 HTTP client 上执行等效配置。

Laravel 文档 Reference


如果您使用 Postman 来测试您的 API,here 是 sanctum 身份验证请求的智能实现。基本上,您必须先获取 sanctum cookie,然后在 XSRF-TOKEN 标头上发送 cookie。