13

When I make a put request in Angular2, I receive the expected set-cookie in the response. However my browser (tried both Chrome and Firefox) refuses to set the cookie.

Instead when I use an Angular 1 app making a call to the same API endpoint, the cookies are set correctly.

The response headers are:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://example.com
Allow:GET, PUT, HEAD, OPTIONS
Content-Type:application/json
Date:Thu, 28 Jan 2016 14:41:38 GMT
P3P:policyref="http://www.example.com/p3p.xml", CP="NON DSP COR CURa TIA"
Server:WSGIServer/0.1 Python/2.7.6
Set-Cookie:sessionid=994wl49qfsizog5bqmt57sgx9q2toa25; expires=Mon, 28-Mar-2016 14:41:37 GMT; Max-Age=5183999; Path=/
Set-Cookie:csrf=u7UQhpAphTsGYKRU6jFlLFt6NoYAhNMS; Domain=api.example.com; expires=Thu, 26-Jan-2017 14:41:38 GMT; Max-Age=31449600; Path=/
Vary:Accept, Cookie

The backend is programmed in Django 1.8.

Does anyone experienced the same thing or have a suggestion how to solve this problem?

Frerk Morrin
  • 729
  • 4
  • 16
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91

3 Answers3

20

Indeed a CORS issue. From Angular2 RC2 on, you just need to

this.http.get('http://my.domain.com/request', { withCredentials: true })
maxbellec
  • 16,093
  • 10
  • 36
  • 43
  • 1
    coresponding angular 2 docs: https://angular.io/docs/ts/latest/api/http/index/RequestOptions-class.html – haja Dec 15 '16 at 09:49
  • Note for anyone like me who read that too quickly here and everywhere else it's advised - that's just a setting that Angular uses, and is given as an attribute of the same object you use to pass in headers. *It's not a header itself.* – HammerN'Songs Jan 03 '19 at 19:48
12

I seems to be a CORS-related issue. Perhaps you could try to set the withCredentials attribute when executing the HTTP request.

This answer could help you to find out how to do that, especially the Cedric Exbrayat's answer:

Edit

You could extend the BrowserXhr:

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = true;
    return <any>(xhr);
  }
}

and override the BrowserXhr provider with the extended:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

If you need more hints about CORS, you could have a look at this link: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/.

Hope it helps you, Thierry

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1

I had the same problem but for me the cookie had a path to '/api/order'.. So only request to this path contained the cookie.. I altered the path to '/' and now everthig is fine..

Simon Ludwig
  • 1,754
  • 1
  • 20
  • 27