【问题标题】:Angular HttpClient does not send domain cookieAngular HttpClient 不发送域 cookie
【发布时间】:2020-10-15 08:49:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular cookies


    【解决方案1】:

    默认情况下,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);
    

    【讨论】:

      【解决方案2】:

      默认情况下,HTTP 不会重新发送 cookie。您必须启用它,无论是使用配置 {withCredentials: true} 的每个请求,还是创建一个 HttpInterceptor 来为所有请求添加它。

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

      或:Stackoverflow: Add credentials to every httpClient call

      【讨论】:

      • 我花了 2 个小时才达到这个目标,但我认为我的代码已损坏
      猜你喜欢
      • 2013-07-02
      • 2021-08-15
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2013-03-30
      相关资源
      最近更新 更多