Laravel Sanctum with SPA:设置 CSRF cookie 的最佳实践

Phi*_*ine 5 laravel laravel-sanctum

目前,我的 SPA 很简单,只有一个联系表。表单数据发送到后端。我为此安装了 Laravel Sanctum。

axios.get('/sanctum/csrf-cookie').then((response) => {
     axios.post('api/contact')
          .then((response) => {
              //doing stuff
          });
});
Run Code Online (Sandbox Code Playgroud)

这工作得很好。然而,我想知道。您在 SPA 中的何时何地触发了获取 CSRF cookie 的初始请求?( axios.get('/sanctum/csrf-cookie'))

我的第一个想法是:

  • 每次安装/加载页面时
  • 仅当您收到419并且您尝试刷新令牌并重试之前的请求时
  • 您不会触发任何 API 请求,只有当用户尝试登录并且您才请求 cookie 时(在我的情况下,我没有任何用户身份验证)
  • 对于每个 API 请求,您可以将其axios.get('/sanctum/csrf-cookie')包裹起来

Phi*_*ine 5

因此,对于未来的读者,我选择:

Only when you receive a 419 and you attempt to refresh the token and retry the previous request

为此,我使用包axios-auth-refresh

我的设置看起来像这样

//bootstrap.js

import axios from 'axios';
import createAuthRefreshInterceptor from 'axios-auth-refresh';

axios.defaults.withCredentials = true;
axios.defaults.baseURL = process.env.GRIDSOME_BACKEND_URL;

const refreshAuthLogic = (failedRequest) => axios.get('/sanctum/csrf-cookie').then((response) => Promise.resolve());

createAuthRefreshInterceptor(axios, refreshAuthLogic, { statusCodes: [419] });

window.axios = axios;
Run Code Online (Sandbox Code Playgroud)