0

I 'm authenticating with site https://a.com. Once I authenticate, I access http://b.com. a.com sets a cookie for the session that I need to send with when I make a get request from b.com to a.com.

Can you please tell me, how I can get the cookie and pass it on with my request.

I have tried sending the requests with "withCredentials": true, Also tried using the axios-cookiejar-support with tough-cookie. But doesn't seem to work.

    .get(a.com/path-requiring-cookie, {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json',
        'access-control-allow-credentials': true,
      },
    })
    .then(res => {
      console.log(res.data);
    });```

This is the code that I have to send the request.

But this doesn't seem to send the cookie with the request.  Can someone please clarify.
hash
  • 3
  • 3

2 Answers2

1

Why don't use a javascript function instead that helps use fetch the Cookie based on it's name like below

function GetCookie(cName) {
  const name = `${cName}=`;
  const decodedCookie = decodeURIComponent(document.cookie);
  const ca = decodedCookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
};

console.log(GetCookie("SID"))
Harsh Makadia
  • 3,263
  • 5
  • 30
  • 42
1

Have a look to this question.

The problem you are trying to solve is to read/send cookies from/to different domains.

One solution, as stated in the previously linked question would be to set some headers on http://b.com

Access-Control-Allow-Origin: http://b.com
Access-Control-Allow-Credentials: true

You do that on the server that has the domain http://b.com

Something along those lines should solve the issue for you.

avcajaraville
  • 9,041
  • 2
  • 28
  • 37