3

Currently, my SPA is simple and has only a contact form. The form data is sent to the backend. I have installed Laravel Sanctum for that.

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

This works perfectly fine. However, I was wondering. Where and which time in your SPA do you fire the initial request to get the CSRF cookie? (axios.get('/sanctum/csrf-cookie'))

My first thoughts were:

  • Every time the page is mounted/loaded
  • Only when you receive a 419 and you attempt to refresh the token and retry the previous request
  • You don't fire any API requests, only when the user tries to log in and only then you are requesting a cookie (in my case I don't have any user authentification)
  • For each API request, you wrap it with axios.get('/sanctum/csrf-cookie') around
4

1 回答 1

3

所以对于未来的读者,我选择了:

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;
于 2020-06-03T10:15:02.807 回答