Laravel sanctum csrf cookie 每个请求?

Laravel sanctum csrf cookie every request?

我正在使用 Laravel 密室(以前的气闸),对此有疑问。我在文档中阅读:

To authenticate your SPA, your SPA's login page should first make a request to the /sanctum/csrf-cookie route to initialize CSRF protection for the application:

axios.get('/sanctum/csrf-cookie').then(response => {
// Login... }); 

Once CSRF protection has been initialized, you should make a POST request to the typical Laravel /login route. This /login route may be provided by the laravel/ui authentication scaffolding package.

这是否意味着对于我发出的每个请求,我应该首先检查是否已经设置了 cookie?因为假设我有一个注册用户。在发出 POST 请求注册用户之前,我应该首先发出 GET 请求以从我的后端获取 CSRF-Cookie,然后发出 POST 请求来注册用户。

现在用户被重定向到登录网页并被要求登录。前端是否首先必须检查是否有 CSRF-Cookie,如果没有,是否应该首先再次发出 GET 请求以获取 cookie?

这最后一点也让我感到困惑,因为当调用注册方法时,用户实际上并没有登录,因此必须将用户重定向到登录页面才能使用用户刚刚填写的凭据登录注册这对我来说似乎是一种糟糕的用户体验,对吗?

当你拿到csrf token后,在接下来的请求中,laravel会自动更新token,所以你不需要在axios.get('/sanctum/csrf-cookie')之后关注这个。

一旦你点击 axios.get('/sanctum/csrf-cookie') API,之后你就不必为每个请求一次又一次地点击它,因为这/sanctum/csrf-cookie会在浏览器上保存 XSRF 令牌Axios 将与请求一起发送。

您可以在这个视频中详细了解它:https://www.youtube.com/watch?v=8Uwn5M6WTe0

我知道自问这个问题以来已经有一段时间了,但是对于在那里搜索的任何人来说,不。您不必为每个请求都调用 /sanctum/csrf-cookie。在发出 post | put | delete... 请求之前,您可以检查是否设置了 XSRF-TOKEN cookie。如果不是,请调用 /sanctum/csrf-cookie 路由(或您配置的任何路由)。请求完成后,(XSRF-TOKEN cookie 将由您的浏览器自动设置)您现在可以继续初始请求。

执行此操作的最佳位置是在拦截器中(如果您的 http 库支持它)。我假设您正在使用 axios。

// Install with 'npm i js-cookie'. A library that helps you manage cookies 
// (or just build your own).
import Cookies from 'js-cookie';

// Create axios instance with base url and credentials support
export const axiosInstance = axios.create({
    baseURL: '/api',
    withCredentials: true,
});

// Request interceptor. Runs before your request reaches the server
const onRequest = (config) => {
    // If http method is `post | put | delete` and XSRF-TOKEN cookie is 
    // not present, call '/sanctum/csrf-cookie' to set CSRF token, then 
    // proceed with the initial response
    if ((
            config.method == 'post' || 
            config.method == 'put' || 
            config.method == 'delete',
            /* other methods you want to add here */
        ) &&
        !Cookies.get('XSRF-TOKEN')) {
        return setCSRFToken()
            .then(response => config);
    }
    return config;
}

// A function that calls '/api/csrf-cookie' to set the CSRF cookies. The 
// default is 'sanctum/csrf-cookie' but you can configure it to be anything.
const setCSRFToken = () => {
    return axiosInstance.get('/csrf-cookie'); // resolves to '/api/csrf-cookie'.
}

// attach your interceptor
axiosInstance.interceptors.request.use(onRequest, null);

export default axiosInstance;

XSRF-TOKEN cookie 带有到期时间。在那之后,浏览器将其删除。因此,只要您能找到 cookie,就可以安全地发出请求,而无需调用 /sanctum/csrf-cookie 或您配置的任何内容。