Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies not sent in cross-origin jquery ajax request when custom header set

We are making an ajax request from our main domain to a subdomain (cross-origin) using jQuery. We have CORS set up, and everything is working until we try to send a custom header with the request. If a custom header is set on the request, then our session cookies are no longer sent with the request.

jQuery version : 2.1.4

Our origin domain: http://example.com

Our session cookies are set up for subdomain use, using domain : .example.com in the cookie options.

CORS headers sent with response from subdomain:

 Access-Control-Allow-Origin : http://example.com
 Access-Control-Allow-Credentials : true
 Access-Control-Allow-Headers : Origin, X-Requested-With, Content-Type, Accept, X-OurCustomHeader

This request works fine (session cookie is sent with request) :

 jQuery.ajax({
       url: 'http://sub.example.com/someajaxroute',
       xhrFields: { withCredentials: true },
 }

This request (with custom header) does not work (session cookie is not sent):

 jQuery.ajax({
       url: 'http://sub.example.com/someajaxroute',
       xhrFields: { withCredentials: true },
       headers : { 'X-OurCustomHeader' : 'xxx'}
 }

Does anyone know why jQuery/browser is not sending the cookies in the second example?


PS. I know there are a lot of jquery CORS questions on stackoverflow. I have looked through them extensively, and cannot find one that addresses this exact problem. I ask that you please only mark as duplicate if you find a question that matches this exact problem. Thank you.

like image 819
UpTheCreek Avatar asked Feb 01 '26 12:02

UpTheCreek


1 Answers

So it turns out (as @KevinB suggested) that it's an issue with the way that preflight OPTIONS are being processed on our server, and nothing to do with the client. Thanks Kevin.

like image 60
UpTheCreek Avatar answered Feb 04 '26 02:02

UpTheCreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!