CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符

新手上路,请多包涵

我有一个涉及的设置

前端服务器(Node.js,域:localhost:3000)<—> 后端(Django,Ajax,域:localhost:8000)

浏览器 <-- webapp <– Node.js(服务应用程序)

浏览器 (webapp) –> Ajax –> Django(服务 ajax POST 请求)

现在,我的问题是 webapp 用于对后端服务器进行 Ajax 调用的 CORS 设置。在 chrome 中,我不断得到

当凭证标志为真时,不能在 Access-Control-Allow-Origin 中使用通配符。

也不适用于Firefox。

我的 Node.js 设置是:

 var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

在 Django 中,我正在使用 这个中间件 和这个

webapp 发出这样的请求:

 $.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

因此,webapp 发送的请求标头如下所示:

 Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

这是响应标头:

 Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

我哪里错了?!

编辑 1:我一直在使用 chrome --disable-web-security ,但现在想让事情真正起作用。

编辑 2: 答案:

所以,我的解决方案 django-cors-headers 配置:

 CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)

原文由 ixaxaar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

这是安全的一部分,你不能这样做。如果您想允许凭据,那么您的 Access-Control-Allow-Origin 不得使用 * 。您必须指定确切的协议 + 域 + 端口。供参考,请参阅以下问题:

  1. Access-Control-Allow-Origin 通配符子域、端口和协议
  2. 使用凭证进行跨域资源共享

此外 * 过于宽松,会破坏凭证的使用。因此将 http://localhost:3000http://localhost:8000 设置为允许来源标头。

原文由 user568109 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你正在使用 CORS 中间件并且你想发送 withCredential 布尔值 true,你可以像这样配置 CORS:

 var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

原文由 Hamid 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题