Unable to use Laravel Sanctum on frontend to generate CSRF cookie
P粉099985373
P粉099985373 2023-08-26 19:05:10
0
1
517
<p>Recently I tried to use Laravel Sanctum for authentication in Nuxt 3 but ran into issues during the initial CSRF cookie handshake. The problem is that after I make a request to the <code>http://localhost:8000/sanctum/csrf-cookie</code> path, the XSRF-TOKEN cookie is not set by the browser. I've been stuck on this problem for a week now and haven't found a solution on the internet. I tried using Axios and Fetch API to set the XSRF-TOKEN without success. I am using <code>http://localhost:8000</code> on the backend and <code>http://localhost:3000</code> on the frontend. Laravel Sanctum itself works fine as when testing on Postman I receive the set-cookie header but not the browser. I set the following properties in the <code>.env</code> file: </p> <pre class="brush:php;toolbar:false;">FRONTEND_URL=http://localhost:3000 SESSION_DOMAIN=localhost:3000 SESSION_DRIVER=cookie</pre> <p>I have made every effort to overcome the limitations of CORS requests on the front end. My fetch function looks like this: </p> <pre class="brush:php;toolbar:false;">window.fetch('http://localhost:8000/sanctum/csrf-cookie', { credentials: 'include', }).then((response) => { console.log(…response.headers) })</pre> <p>I've read that setting the credentials to 'include' can solve the problem, but even with that, I still can't set the XSRF-TOKEN. I tried setting the credentials to 'same-origin' but that didn't work either. Does anyone know how to solve this problem? </p>
P粉099985373
P粉099985373

reply all(1)
P粉002546490

The problem is that the browser will not accept cookies from different ports.

Since your backend runs on port 8000 and the frontend runs on port 3000, the cookies provided by the backend will not be set on the frontend.

Therefore, a workaround is to disable CSRF protection only for API endpoints. You can do this in the VerifyCsrfToken middleware.

Add this line to your $except array and you're good to go.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!