search

Home  >  Q&A  >  body text

Unable to use Laravel Sanctum on frontend to generate CSRF cookie

<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粉099985373P粉099985373465 days ago599

reply all(1)I'll reply

  • P粉002546490

    P粉0025464902023-08-27 10:38:36

    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.

    reply
    0
  • Cancelreply