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

我有一个设置涉及

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

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

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

现在,我的问题在于CORS设置,Web应用程序使用Ajax调用后端服务器。 在铬,我不断得到

当凭证标志为真时,不能在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中,我正在使用这个中间件

Web应用程序提出请求:

 $.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:答案:

所以,我的解决schemedjango-cors-headers config:

 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/ ) 

这是安全的一部分,你不能这样做。 如果您要允许凭证,则Access-Control-Allow-Origin不得使用* 。 你将不得不指定确切的协议+域+端口。 参考看这些问题:

  1. Access-Control-Allow-Origin通配符子域名,端口和协议
  2. 与证书交叉起源资源共享

此外*太宽松,并会打败证书的使用。 因此,设置http://localhost:3000http://localhost:8000作为允许源标头。

如果你使用express你可以使用cors包来允许CORS这样写,而不是写中间件;

 var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); app.get(function(req,res){ res.send('hello'); }); 

如果您正在使用CORS中间件,并且想要使用withCredential布尔值true发送,则可以像这样configurationCORS:

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