74

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?

LF00
  • 27,015
  • 29
  • 156
  • 295
Tim Daubenschütz
  • 2,053
  • 6
  • 23
  • 39

2 Answers2

138

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

Mechlar
  • 4,946
  • 12
  • 58
  • 83
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
  • 6
    This and setting the backend header to Allow-Credentials fixed the problem! Thanks! – Tim Daubenschütz Jun 12 '13 at 12:43
  • 11
    Just to add to this, I noticed when I did a call like `$http.get('something', { withCredentials: true})` the browser wouldn't send the cookies. However, using the above code to add `withCredentials` to the defaults did the trick. Not sure why but hopefully that helps if someone else runs across this problem – David Savage May 05 '14 at 22:13
  • 4
    It still doesn't work for me. What I am doing is that the server set an httpOnly cookie on my first response, when I send the second request, the cookies set for the first response has never been attached to the second request. –  Oct 20 '14 at 05:32
  • 1
    It is working in localhost, but when I moved to a server it not working. Why it is not sending cookie in server? – Abhilash Augustine Nov 26 '15 at 09:46
11
$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.

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • 1
    This approach worked for me in AngularJS2....but not untill after the session I created before changing my source code expired! – Dave Aug 08 '16 at 15:17