I use Laravel Sanctum to authorize SPA application requests (NuxtJS). In general, I understood the idea with the /sanctum/csrf-cookie
endpoint and am already sending a request using axios, which installs the XSRF TOKEN once before the user logs in, and then uses it for API methods while the session is alive and the XSRF-TOKEN itself is valid.
But I get the following result: Laravel generates a Set-Cookie XSRF-TOKEN header with each API request that I send before I go to /sanctum/csrf-cookie
. For example: when the main page loads, 4 requests are sent (to receive data from the backend for rendering content). So each response to this request has a Set-Cookie XSRF-TOKEN header and overwrites it each time.
Here is an example of one of the server response header:
At the same time, the Set-Cookie response headers /sanctum/csrf-cookie
look strange: it not only returns a new XSRF-TOKEN (as all API requests do for some reason), but also returns some_uuid=something similar to XSRF-TOKEN.
My front-end and backend work locally in docker-compose, so SANCTUM_STATEFUL_DOMAINS=localhost
(although I tried to specify different values there, it didn't help).
I also tried specifying the FRONTEND_URL and changing the session settings. By the way, here they are (listed by "/" what I tried):
SESSION_DRIVER=cookie/redis/database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null/localhost
I use Laravel 11 and in my bootstrap/app.php
specified by $middleware->statefulApi();
; routes I tried has "api" middleware; axios config has withCredentials: true
, withXSRFToken: true
What could be the problem and how to reduce the overhead of the backend (useless generation of a bunch of tokens for each request), as well as eliminate the problems with token synchronization on the front-end that this problem may cause?
Problem resolved here:
The XSRF token is encrypted and in fact it is the same token.
You cannot and should not disable Laravel's Set Cookie header, which it sends to SPA API requests (for my case with CSRF-protection).
The /sanctum/csrf-cookie
is needed in order to be sure that the SPA has a token, because it may not send GET requests when the page loads, as in my case