I have an application with a Laravel backend using Sanctum. For the frontend, I use Nuxt3 with nuxt-auth-sanctum.
When I run the frontend and backend on my local machine, everything works fine, and I can log in. For the local frontend, I use http://localhost:2765, and the backend is http://127.0.0.1:8000 (which is the same as localhost:8000).
Now, I want to call the backend on a web server with the URL https://dev.domain.de. Because I have to use the same domain, I now start the local frontend with http://local.domain.de:2765.
I get the token correctly from https://dev.domain.de/sanctum/csrf-cookie, but the login route doesn’t have the correct token, and I get a 419 error with "CSRF token mismatch."
I tried to get the cookie with useCookie(‘XSRF-TOKEN’). With the local-only version, it works, but with the second version, it doesn’t work.
In the Sanctum config, I have:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s%s',
'admin.domain.de,localhost:2765,local.domain.de:2765',
Sanctum::currentApplicationUrlWithPort(),
env('FRONTEND_URL') ? ','.parse_url(env('FRONTEND_URL'), PHP_URL_HOST) : ''
))),
Session config:
'domain' => env('SESSION_DOMAIN', 'domain.de'), // local/web version
SESSION_DOMAIN=localhost // local-only version
'same_site' => env('SESSION_SAME_SITE', 'lax'),
'http_only' => env('SESSION_HTTP_ONLY', true),
Here is a screenshot of the local version that is okay:
What do I need to change in the configs so that I can use the token from the cookie?
I tried for example this:
SESSION_DOMAIN=.domain.de
or:
SESSION_SAME_SITE=none
2
Answers
I think the problem was to call the api with https from the local http frontend
On the dev script in the package.json i added "--https true" and now i have also on the local nuxt page with https
If you get a 419 error, you might have the incorrect CORS configuration. Here you can find more details about the proper configuration of the Laravel app for nuxt-auth-sanctum – https://manchenkoff.gitbook.io/nuxt-auth-sanctum/authentication/spa-cookie.
Usually, the problem is that the frontend domain is not included in the
allowed_origins
orstateful
domain list.Feel free to open an issue in the GitHub repo in case of any problems, I will try to help!