Angular + Node + Express + Passport + oauth2orize独特的CORS问题

时间:2015-02-05 17:37:46

标签: angularjs node.js express passport.js oauth2orize

我已经构建了一个用于本地身份验证和Facebook身份验证的API。

我正在使用节点明确护照 oauth2orize 进行授权。

我现在正在通过终端应用程序和API测试套件完美地运行API,但是,当从角度调用我的身份验证端点时,我会收到以下内容:

本地身份验证

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

http://localhost:4200/oauth2/auth
    ?client_id=[CLIENT_ID]
    &redirect_uri=http:%2F%2Flocalhost:4200%2Foauth2%2Fauth%2Fcallback (http://localhost:4200/oauth2/auth/callback)
    &response_type=code.

This can be fixed by moving the resource to the same domain or enabling CORS.

Facebook身份验证:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

https://www.facebook.com/dialog/oauth
    ?response_type=code
    &redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fauth%2Ffacebook%2Fcallback (http://localhost/auth/facebook/callback)
    &client_id=[CLIENT_ID].

This can be fixed by moving the resource to the same domain or enabling CORS.

过去我遇到过CORS问题,并整合了https://www.npmjs.com/package/cors

中的 npm ' cors '中间件模块

CORS init:

var cors = require('cors');
api.use(cors());

根据我之前的问题,这已经足够了,但是,这些新的CORS问题并没有帮助。

我也注意到,在Firefox中,如果我点击错误消息,就会打开一个新的对话窗口,服务器会继续正确地授权用户。

有人可以帮忙吗?

更新1:

检查注释以获取调试信息的屏幕截图。

更新2:

登录流程中执行的最后2个请求的响应标头。

  1. 204

    Access-Control-Allow-Credentials: true
    Connection: keep-alive
    Date: Fri, 06 Feb 2015 15:26:43 GMT
    Vary: Origin
    X-Powered-By: Express
    access-control-allow-headers: authorization
    access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
    access-control-allow-origin: http://localhost:8100
    
  2. 302

    Access-Control-Allow-Credentials: true
    Connection: keep-alive
    Content-Length: 138
    Content-Type: text/plain; charset=utf-8
    Date: Fri, 06 Feb 2015 15:26:43 GMT
    Location: http://localhost:4200/oauth2/auth/callback?code=[CODE_HERE]
    Set-Cookie: connect.sid=[SID_HERE]; Path=/; HttpOnly
    Vary: Origin, Accept
    X-Powered-By: Express
    access-control-allow-origin: http://localhost:8100
    

1 个答案:

答案 0 :(得分:0)

文档中较早的示例不包括处理预检请求,也不指定任何来源,如果您要发送带有请求的任何凭据(例如,您的授权标头),则需要这些来源。这是一个例子:

var whitelist = ['https://localhost:4200']; // Acceptable domain names. ie: https://www.example.com
var corsOptions = {
  credentials: true,
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
    // callback(null, true); uncomment this and comment the above to allow all
  }
};

// Enable CORS
app.use(cors(corsOptions));
// Enable CORS Pre-Flight
app.options('*', cors(corsOptions));