0

hi everyone i have two separated projects frontend(react js) backend(laravel 8). so i want to sent a post request to (/login) in web.php file and as laravel docs clarify i have to make axios.get(/sanctum/csrf-cookie) before axios.post(). My problem is that post return 'CSRF token mismatch' i have tried a lot of solutions but i still have the problem.

this is csrf-cookie network

screenshot

this is login network

screenshot

it seems that axios doesn't include xsrf-token in post automatically. please someone help me and clarify for if it necessary to use csrf in this case.

user41vall
  • 11
  • 1
  • 3
  • 1
    Does this answer your question? [How to set header and options in axios?](https://stackoverflow.com/questions/45578844/how-to-set-header-and-options-in-axios) – Code Spirit Mar 28 '22 at 22:23
  • 1
    Check the request headers (the first tab), not the response cookies for your `/login` request. There you should see the Cookie header and potentially the `X-XSRF-TOKEN` header. Compare them to the value you got back from the first request – Phil Mar 28 '22 at 22:26
  • 1
    Also, please [edit] your question to share your actual code. Perhaps you aren't waiting for the first request to complete before making the second one – Phil Mar 28 '22 at 22:28
  • 1
    Are the frontend and backend on the same domain? – Travis Britz Mar 28 '22 at 22:35
  • @TravisBritz yes they are on the localhost , react with port 3000 and laravel port 8000. But the cookies returned by get(/sanctum/csrf-cookie) returned to localhost :8000 instead of localhost:3000 – user41vall Mar 29 '22 at 11:26
  • Different ports are considered to be different sites in terms of browser permissions for accessing site data like cookies. axios might only set the `X-XSRF-TOKEN` header automatically for requests on the same site. Check that the header is being sent to the login endpoint, and if it's not, check that your frontend can read the `XSRF-TOKEN` cookie value set by the backend. If it can at least read the cookie, then you can configure axios to automatically attach the header. – Travis Britz Mar 30 '22 at 02:29
  • Also, if your frontend will be served from the same domain on your production environment then it might be worth configuring your frontend's dev server on localhost:3000 to proxy for all requests to localhost:8000, so that it can function the same way on your local environment as it would on production. Otherwise, if your frontend/backend will be on *different* domains on production, then your time might be better spent configuring CORS settings, because the same issue you have now will occur on production later. – Travis Britz Mar 30 '22 at 02:35

0 Answers0