Search code examples
javascriptjquerycookiessession-cookiessetcookie

Cookie is not sent with JavaScript on POST request


I want to use a secure cookie which is stored by the browser when accessing the endpoint /access on my website. The cookie is saved during the login process and I made sure that my website runs on a subdomain of my backend (which creates the cookies for the clients).

My backend is running on www.welovecoding.com and my web application is hosted on webapp.welovecoding.com.

The cookie which I receive from my backend looks like this:

Set-Cookie:user_id=RLXXWNCGAyVBmnogfiE1ngFCpBRKA48YaFOGyrPypwvU3eZCA==; Path=/access; Expires=Tue, 29-Sep-2015 17:37:11 GMT; Domain=.welovecoding.com; HttpOnly; Secure

What I want to do now is a POST request on www.welovecoding.com/access with my cookie as authentication credentials. I am sending withCredentials when executing my AJAX request with jQuery:

$.ajax({
  crossDomain: true,
  type: 'POST',
  url: "http://www.welovecoding.com/access",
  xhrFields: {
    withCredentials: true
  }
}).done(function (data, textStatus, jqXHR) {
  console.log("Response", data);
});

But I still do get a HTTP error 403 which says that the cookie is missing. Does anyone know why? Maybe because the cookie has HttpOnly and Secure set?


Solution

  • Yes, it's because the cookie has Secure set - and you are posting to http

    ;secure (cookie to only be transmitted over secure protocol as https)
    

    https://developer.mozilla.org/en-US/docs/Web/API/document.cookie