Angular HttpClient does not send domain cookie

喜欢而已 提交于 2020-12-06 09:00:47

问题


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://tools.ietf.org/html/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?


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/59616290/angular-httpclient-does-not-send-domain-cookie

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!