Oliver
Oliver

Reputation: 36393

Cookies are not sent on HTTP GET

I am using HTTP Only (and secure in production) cookies to maintain a users authentication state with a backend API.

I've run into an issue however where the Cookies are NOT being sent on HTTP GET requests. POST and PATCH requests work perfectly, but gets are missing the Cookies request headers.

I've seen nothing about this being a specific limitation as part of the standards. The Mozilla documentation explicitly has an example with a GET request including Cookies? https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

As context I am currently in development and so running on "localhost" and using Chrome 63.0.3239.132.

Edit: Added images

So cookies are set in the application

Cookies Set

PATCH request sends the Cookies as expected

Patch Working, sending cookies as expected

GET request includes nothing. I threw the 404 because I could not find the cookie values.

Get Not Working, no cookies are sent

Upvotes: 3

Views: 4712

Answers (1)

Oliver
Oliver

Reputation: 36393

The issue was with the javascript (actually Typescript) code making the AJAX request using JQuery.

Cookies are considered credentials and therefore the XHR request must allow withCredentials=true.

let ajax = this.jQuery.ajax({
  type: "GET",
  url: getUrl,
  headers: this.generateHeaders(),
  xhrFields: {
    withCredentials: true // this was false.
  },
  timeout: this.options.RequestTimeoutMs
});

After changing the withCredentials field cookies were sent!

Side Note: on withCredentials. You will require CORS settings to allow this, specifically Access-Control-Allow-Credentials:true at which point you cannot use Access-Control-Allow-Origin:* (not a good idea anyway) but instead will have to specify domains with no trailing /'s

Upvotes: 5

Related Questions