7

I have an Angular app that runs on angular.example.com. The API runs on app.example.com. I get a domain cookie from app.example.com that sets the cookie on .example.com containing a JWT token (the cookie should be shareable between these domains according to RFC: https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.3).

When the request to angular.example.com is sent and I can see the cookie as part of the request headers (added by the browser). The Angular app is served and makes a request to app.example.com to fetch some data.

I would expect that the cookie would be send along with this request by the browser, but it doesn't happen. Can anyone explain why this doesn't happen?

Community
  • 1
  • 1
Pascal
  • 305
  • 2
  • 4
  • 15

2 Answers2

15

XHR requests in Angular by default do not pass cookie information with each request. What this means is by default Angular doesn't pass Cookies captured on previous requests back to the server which effectively logs out the user.

And your server response must allow headers Access-Control-Allow-Credentials.

In order for that to work the HttpClient has to set the withCredentials:

CORS - Allow-Origin-With-Credentials

In addition to the client side withCredentials header, if you are going cross domain also make sure that the Allow-Origin-With-Credentials header is set on the server. If this header is not set the client side withCredentials also has no effect on cross-domain calls causing cookies and auth headers to not be sent.

let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post(this.url, body , options);
Community
  • 1
  • 1
Sadaf Niknam
  • 509
  • 1
  • 4
  • 14
13

HTTP does not resend cookies by default. You have to enable it, either per request with the config {withCredentials: true}, or create an HttpInterceptor to add it for all requests.

this.httpclient.get(myUrl, {withCredentials:true})

or: Stackoverflow: Add credentials to every httpClient call

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
Sharondio
  • 2,605
  • 13
  • 16