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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With