$http doesn't send cookie in Requests

HtmlAngularjsWebkitXmlhttprequest

Html Problem Overview


We are working on a RESTful Webservice with AngularJS and Java Servlets. When the user logs in, our backend sends a "Set-Cookie" header to the frontend. In Angular we access the header via $cookies (ngCookie - module) and set it. enter image description here

Now that the user is logged in he can for example delete some stuff. Therefore the frontend sends a GET request to the backend. Because we work on different domains we need to set some CORS Headers and Angular does an OPTIONS request before the actual GET request:

OPTIONS request: OPTIONS request

GET request GET request

We do this in Angular via $http module, but it just won't send the cookie, containing JSESSIONID.

How can I enable Angular to send cookies?

Html Solutions


Solution 1 - Html

In your config, DI $httpProvider and then set withCredentials to true:

.config(function ($httpProvider) {
	$httpProvider.defaults.withCredentials = true;
	//rest of route code
})

Info on angularjs withCredentials: http://docs.angularjs.org/api/ng.$http

Which links to the mozilla article: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#section_5

Solution 2 - Html

$http.get("URL", { withCredentials: true })
  .success(function(data, status, headers, config) {})
  .error(function(data, status, headers, config) {});

Another thing to keep in mind: You need to have 3rd party cookies enabled. If you have it globally disabled in Chrome, click on the "i"-Symbol to the left of the domain name, then cookies, then "blocked" and unblock the target domain.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim DaubenschützView Question on Stackoverflow
Solution 1 - HtmlMathew BergView Answer on Stackoverflow
Solution 2 - HtmlDaniel FView Answer on Stackoverflow