添加 Stormpath Angular SDK 后出现 CORS 问题

Issue with CORS after adding Stormpath Angular SDK

我正在开发 SPA MEAN 应用程序,我正在针对 Apiary 模拟 API 开发它,它具有以下 CORS headers 集:

Access-Control-Allow-Methods → OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
Access-Control-Allow-Origin → *
Access-Control-Max-Age → 10

一切正常,angular 可以使用 $http angular 服务访问它。但是在添加 Stormpath Angular SDK 之后,所有这些请求都失败并出现以下错误:

XMLHttpRequest cannot load https://xxx.apiary-mock.com/workshops?type=favourite. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:8000' is therefore not allowed access.

我想弄清楚为什么这些请求被拒绝以及这些 headers 是在什么时候添加的?

我知道如何解决这个问题,将这些 headers 添加到养蜂场:

+ Response 200 (application/json)

    + Headers

            Access-Control-Allow-Credentials: true
            Access-Control-Allow-Methods: OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
            Access-Control-Allow-Origin: http://localhost:8000

我仍在尝试弄清楚 Stormpath 在哪里使那些 headers 成为必需的。

任何时候您有一个 SPA 客户端从一个域(例如 localhost:8080)提供服务并且您希望该客户端访问另一个域(xxx.apiary-mock.com)上的 API,浏览器要求服务器域正确添加CORS headers。

如果客户端域和服务器域不同,浏览器的安全模型要求服务器通过设置 Access-Control-Allow-Origin 响应 header 来指示哪些客户端域可以访问服务器(除了其他相关的Access-Control-* headers).

感谢您发现这个问题。 Stormpath Angular SDK 确实有一个拦截器,它为所有请求设置 withCredentials: true 标志。请看代码here.

目的是确保始终发送我们的身份验证 cookie,即使在跨域情况下也是如此。但如果您的 Angular 应用程序正在与不需要发送 cookie 的其他 API 通信,我可以看出这会带来怎样的问题。

作为解决方法,您可以通过简单地添加另一个来覆盖我们的拦截器:

angular.module('myapp', [
  'stormpath',
  'stormpath.templates'
]).config(function ($httpProvider) {
  $httpProvider.interceptors.push(function() {
    return {
      request: function(config) {
        config.withCredentials=false;
        return config;
      }
    };
  });
});

我创建了一个问题来讨论更好的解决方案:https://github.com/stormpath/stormpath-sdk-angularjs/issues/72