Cross domain POST request is not sending cookie Ajax Jquery
There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.
To have a cookie sent by the browser to another site during a request the following criteria must be met:
- The
Set-Cookie
header from the target site must contain theSameSite=None
andSecure
labels. IfSecure
is not used theSameSite
header will be ignored. - The request must be made to a
https
endpoint, a requirement of theSecure
flag. - The
XHRRequest
must be made withwithCredentials=true
. If using$.ajax()
this is accomplished with thexhrFields
parameter (requiringjQuery=1.5.1+
) - The server must respond with
Access-Control-Allow-Origin
header that matches the requestOrigin
header. (*
will not be respected in this case)
A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.
Please note this doesn't solve the cookie sharing process, as in general this is bad practice.
You need to be using JSONP as your type:
From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
$.ajax(
{
type: "POST",
url: "http://example.com/api/getlist.json",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
},
success: function(){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials
only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie
header.