Angular HttpClient 不发送域 cookie

Pas*_*cal 4 cookies angular

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

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

我希望 cookie 会与浏览器的这个请求一起发送,但它不会发生。谁能解释为什么这不会发生?

Sha*_*dio 13

HTTP 默认情况下不会重新发送 cookie。您必须使用 config 为每个请求启用它{withCredentials: true},或者创建一个HttpInterceptor为所有请求添加它。

this.httpclient.get(myUrl, {withCredentials:true})
Run Code Online (Sandbox Code Playgroud)

或者:Stackoverflow:向每个 httpClient 调用添加凭据


Sad*_*nam 8

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

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

为了使其工作,HttpClient 必须设置withCredentials

CORS - Allow-Origin-With-Credentials

除了客户端 withCredentials标头之外,如果您要跨域,还要确保在服务器上设置了Allow-Origin-With-Credentials标头。如果未设置此标头,客户端withCredentials也不会影响跨域调用,从而导致不发送 cookie 和 auth 标头。

let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post(this.url, body , options);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,当设置“Allow-Origin-With-Credentials”时,来源不能为“*”。 (2认同)