HttpClient不发送域cookie

HttpClient不发送域cookie

本文介绍了Angular HttpClient不发送域cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 angular.example.com 上运行的Angular应用程序.该API在 app.example.com 上运行.我从 app.example.com 获得了一个域cookie,该域cookie在包含JWT令牌的 .example.com 上设置了cookie(根据RFC,cookie应该在这些域之间可共享): https://tools.ietf.org/html/rfc6265#section-4.1.2.3 ).

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

当发送到 angular.example.com 的请求时,我可以看到cookie作为请求标头的一部分(由浏览器添加).Angular应用程序将被投放,并向 app.example.com 发出请求以获取一些数据.

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.

我希望浏览器可以将cookie与该请求一起发送,但是不会发生.谁能解释为什么这种情况不会发生?

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?

推荐答案

默认情况下,Angular中的XHR请求不会在每个请求中传递cookie信息.默认情况下,这意味着Angular不会将先前请求捕获的Cookie传递回服务器,从而有效注销用户.

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.

并且您的服务器响应必须允许标头 Access-Control-Allow-Credentials .

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

为此,HttpClient必须设置 withCredentials :

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

除了客户端 withCredentials 标头外,如果要跨域访问,还请确保在服务器上设置了 Allow-Origin-With-Credentials 标头.如果未设置此标头,则客户端 withCredentials 也不会影响跨域调用,从而导致Cookie和auth标头无法发送.

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

这篇关于Angular HttpClient不发送域cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:52