coviex
coviex

Reputation: 513

jQuery does not send Cookie to server

Cross-domain problem. From HTTP to same domain HTTPS.

Server requires X-Requested-With header so I set it in jQuery ajax options:

'headers': {'X-Requested-With': 'XMLHttpRequest'}

jQuery sends OPTION then:

OPTIONS /my/test/ HTTP/1.1
Host: www.my.dev
Origin: http://www.my.dev
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with

Server responds:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: x-requested-with
Access-Control-Allow-Credentials: true

Then jQuery sends "actual" request:

POST /my/test/ HTTP/1.1
Host: www.test.dev
X-Requested-With: XMLHttpRequest
Origin: http://www.test.dev

Cookie header is missing!

Server responds with:

HTTP/1.1 403 Forbidden
Content-Type: application/json
Set-Cookie: SESSID=3tg8svt3lrv97v155uv2kqr3o2; expires=Sat, 25-Apr-2015 17:35:13 GMT; Max-Age=259200; path=/

Adding

    'xhrFields': {
        'withCredentials': true
    },
    'crossDomain': {
        'crossDomain': true
    },

to jQuery ajax options results in jQuery not sending actual request at all, only OPTIONS.

How to send cookie? Could at least someone confirm that cookies are sent in similar setup?

Upvotes: 0

Views: 1442

Answers (1)

coviex
coviex

Reputation: 513

Made it work.

Some important notes:

  • crossDomain does not seem to do anything
  • if you have withCredentials in ajax options but do not have Access-Control-Allow-Credentials in OPTIONS response then actual request is not made
  • if you do not have withCredentials jQuery does not send Cookie header
  • if you do not send Cookie in actual request then server does not send Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers back
  • response to actual request must have Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers - otherwise jQuery does not parse response body (though it sees response code and all headers alright) and throws an error to console
  • having cookie domain not set does not change anything
  • headers letter case does not matter though jQuery lowercases forced header name

PS

  • I'm not sure but I guess jQuery does not add anything extra special here so jQuery = browser
  • server: nginx 1.7.6, PHP 5.5.24; browsers: FF31, Chrome42; jquery 2.0.3

Upvotes: 1

Related Questions