Cross domain POST request is not sending cookie Ajax Jquery
Solution 1
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.
Solution 2
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);
}
}
);
Solution 3
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.
Solution 4
I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.
Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.
I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session
Kirill Reva
Updated on March 28, 2020Comments
-
Kirill Reva about 4 years
Seems that something similar already has been discussed on stackoverflow, but i could not find exactly the same.
I am trying to send Cookie with CORS(Cross-origin resource sharing), but it is not working.
This is my code.
$.ajax( { type: "POST", url: "http://example.com/api/getlist.json", dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true, beforeSend: function(xhr) { xhr.setRequestHeader("Cookie", "session=xxxyyyzzz"); }, success: function(){ alert('success'); }, error: function (xhr) { alert(xhr.responseText); } } );
I dont see this cookie in request HEADER.
-
Kirill Reva over 11 yearsThanks @Justin Schuhmann Actually i indeed need to make CORS request , not JSONP. Does not CORS support cookie passing?
-
Kirill Reva over 11 yearsThat is really strange. Why i can not pass cookies in the Header?
-
monsur over 11 yearsAlthough 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.
-
Kirill Reva over 11 yearsThanks everybody. Seems there is no to discuss here.
-
Eswar Rajesh Pinapala over 10 yearsHi, Actually using dataType: "text", worked for me like a charm! Thanks!
-
chovy over 10 yearsso how do we set them with
Set-Cookie
on the server/client making the request? -
Dominik Goltermann about 10 yearsThe cookies get set automatically, but are not readable by the webpage you sent the cors request from, because it's on another domain. if you issue another cors request the browser will however automatically append the cookie to the request (if withCredentials is set to true!!). The only thing that's different from normal ajax requests ist that you can't read the cookie content with JavaScript.
-
Mnebuerquo over 9 yearsWhat is bad practice? Using cookies in CORS requests? If so, why is it bad practice?
-
abc123 over 9 years@Mnebuerquo I'm sorry? cookie sharing is a bad practice, unless it is to sub-domains. Because a cookie isn't secure, so just send the necessary data over the AJAX call. Other than sending them as "security" i don't know why you'd waste your time with thme.
-
Mnebuerquo over 9 yearsI see. I didn't realize the OP was trying to send a cookie to a different domain than that which set it. Javascript being able to send cookies to a different domain would enable all kinds of session hijacking. Ideally you'd make your cookies http-only so the javascript can't touch them at all. I must have been sleeping when I read this the first time. Thanks!
-
asgs almost 8 yearsI've not set withCredentials, so the subsequent requests don't seem to be sending the cookie back to the remote server. After I set
withCredentials
, I'm getting an error in Chrome thatXMLHttpRequest cannot load <XXX>. Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '<YYY>' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
where XXX is remote and YYY is local. -
Mollo about 4 yearsIs this solution secure? I feel like it has a security breach. I'm not sure if it's recommended to store the session ID in the sessionStorage
-
meawoppl about 4 yearsSo, a couple other things. The request must return the
Access-Control-Allow-Origin
which corresponds to that of the requester (not *). On Chrome now you must also specify ["SameSite=None", "Secure"] in the set-cookie request too! -
meawoppl about 4 yearsI posted an answer below that clarifies some of the modern needs here.
-
meawoppl about 4 yearsThis likely won't work any more. blog.chromium.org/2019/05/… Take a look at the answer I posted below which clarifies some of the changes made recently in chrome
-
meawoppl about 4 yearsThis approach does not work for serverless type applications, where jwt tokens are used as cookies...
-
QuantumBlack over 3 yearsIn case of a XMLHttpRequest (which adds a
X-Requested-With
header) you might also need to set theAccess-Control-Allow-Headers
toX-Requested-With
serverside otherwise CORS policy might block the request -
edoedoedo over 2 yearsstoring the session id in the storage kills the whole security measure of exchanging a secure cookie inaccessible from javascript