-1

I am using Laravel sanctum to make auth With ReactJS in cors.php. I have set these values

'paths' => ['api/*', 'api/csrf-cookie','/login'],
'supports_credentials' => true,

sanctum.php

'prefix'=>'api'

in React I use axios with credintials

axios.get('http://www.react.test/api/csrf-cookie').then(response => {
        console.log(response);
 }, { withCredentials: true });

when using Postman, I get the Set-Cookie Value , but when I try to use browser its not set in my browser under Application->cookies tab

  • Laravel domain
http://www.react.test/
  • React domain
http://localhost:3000/
bhucho
  • 3,903
  • 3
  • 16
  • 34
cEthar
  • 9
  • 2
  • I am not sure, I saw a similar question a few hours ago, but I think it is related to CORS, you are "talking" between 2 different domains, so cookies cannot be created except CORS explicitly allows this to happen for THAT domain or ALL domains. – matiaslauriti Sep 05 '21 at 23:11
  • 1
    @matiaslauriti he needs to use the axios package properly, after that, CORS is not the issue here – Sachin Ananthakumar Sep 06 '21 at 00:46
  • @cEthar I have answered your question, you can mark it as answered and upvote it if this solved your issue, thankyou – Sachin Ananthakumar Sep 06 '21 at 00:47
  • @SachinAnanthakumar oh, I know about `withCredentials` but I thought for a moment that you could pass it like the author was doing... – matiaslauriti Sep 06 '21 at 00:52
  • @matiaslauriti, you can't pass it like that, the author passed it as a second argument to `then`, The second argument to `then` is for error, refer [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) – Sachin Ananthakumar Sep 06 '21 at 01:01
  • please mark the answer as answered if it solves the problem, thankyou! – Sachin Ananthakumar Sep 06 '21 at 01:02
  • @SachinAnanthakumar no its not solved, when i put link in browser directly, its work successfully, but the problem when use axios. – cEthar Sep 06 '21 at 11:41

3 Answers3

1

You are using axios package wrong, withCredentials should be given as a config options to axios and not a then,

Change your code to this

axios.get('http://www.react.test/api/csrf-cookie',{ withCredentials: true }) // FIX
.then(response => {
    console.log(response);
}).catch((err)=>{
   console.log(err);
});

This will work fine now

For more refer to axios

0

I solved this issue by changing the domain from 'http://www.react.test/api/csrf-cookie to http://localhost:8000/api/csrf-cookie

I think domain must be https if it's not a localhost.

JW Geertsma
  • 857
  • 3
  • 13
  • 19
cEthar
  • 9
  • 2
0

cookies only work for the same domain or subdomain for security reasons

osama Abdullah
  • 193
  • 1
  • 12