简体   繁体   English

Chrome将Origin标头添加到同源请求中

[英]Chrome adding Origin header to same-origin request

We're POSTing an AJAX request to a server running locally, ie 我们正在向本地运行的服务器发布一个AJAX请求,即

xhr.open("POST", "http://localhost:9000/context/request");
xhr.addHeader(someCustomHeaders);
xhr.send(someData);

The page that this javascript is being executed is also being served from localhost:9000, ie this totally looks like a same-origin request. 正在执行此javascript的页面也是从localhost:9000提供的,即这看起来像一个同源请求。

However, for some reason, Google Chrome always sets an Origin header in the resulting request, causing our server to block the request based on the false assumption that it's CORS request. 但是,出于某种原因,Google Chrome总是在生成的请求中设置一个Origin标头,导致我们的服务器根据它的CORS请求的错误假设来阻止请求。

This does not happen in Firefox. 这在Firefox中不会发生。

Also, neither Firefox nor Chrome are sending an OPTIONS preflight request, which is confusing; 此外,Firefox和Chrome都没有发送OPTIONS预检请求,这令人困惑; why set an Origin header without first preflighting to make sure the the Origin and the Custom headers are allowed by the server? 为什么在没有首次预检的情况下设置Origin标头以确保服务器允许Origin和Custom标头?

Does anyone know what is going on in this case? 有谁知道在这种情况下发生了什么? Are we misunderstanding the CORS spec? 我们是否误解了CORS规范?

Chrome and Safari include an Origin header on same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header). Chrome和Safari在同源POST / PUT / DELETE请求中包含Origin标头(同源GET请求不具有Origin标头)。 Firefox doesn't include an Origin header on same-origin requests. Firefox在同源请求中不包含Origin标头。 Browsers don't expect CORS response headers on same-origin requests, so the response to a same-origin request is sent to the user, regardless of whether it has CORS headers or not. 浏览器不期望同源请求上的CORS响应头,因此对同源请求的响应将发送给用户,无论它是否具有CORS头。

I would recommend checking the Host header, and if it matches the domain in the Origin header, don't treat the request as CORS. 我建议检查Host标头,如果它与Origin标头中的域匹配,请不要将请求视为CORS。 The headers look something like this: 标题看起来像这样:

Host: example.com
Origin: http://example.com

Note that Origin will have the scheme (http/https), domain and port, while Host will only have the domain and port. 请注意, Origin将具有方案(http / https),域和端口,而Host将只具有域和端口。

According to RFC 6454 - The Web Origin Concept - the presence of Origin is actually legal for any HTTP request, including same-origin requests: 根据RFC 6454 - Web Origin Concept - Origin的存在实际上对任何HTTP请求都是合法的,包括同源请求:

http://tools.ietf.org/html/rfc6454#section-7.3 http://tools.ietf.org/html/rfc6454#section-7.3

"The user agent MAY include an Origin header field in any HTTP request." “用户代理可以在任何HTTP请求中包含Origin头字段。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM