Which server needs to return Access-Control-Allow-Origin header?

一笑奈何 提交于 2019-12-13 12:33:36

问题


Let's say I have an HTML page, served up from example.com. It makes an javascript ajax request to targetServer.com

Which server needs to return a Access-Control-Allow-Origin="(something)"?

Is it the targetServer or the server that served up the original HTML page (i.e. example.com)?

[I know this probably is obvious, but the docs on the web seem to imply the targetServer has to send and allow-origin header of "example.com" But if this is a security feature, wouldn't a malicious targetServer.com always serve up a suitable allow-origin header? It sort of makes sense that example.com would give the browser a list of server it is allow to call in addition to example.com]


回答1:


The target server needs to set the Access-Control-Allow-Origin header.

CORS is meant to protect a server from unexpected cross-origin requests. In a world before CORS existed, servers were protected from cross-origin requests by the browser's same-origin policy. If CORS were automatically allowed to all servers, this same-origin contract would break, and servers would being receiving unexpected requests. In order to prevent this, the CORS spec authors put the servers in charge of dictating what types of cross-origin requests are allowed.

Servers can do this not only with the Access-Control-Allow-Origin header, but also with the Access-Control-Allow-Credentials, Access-Control-Allow-Methods, Access-Control-Allow-Headers and Access-Control-Expose-Headers headers. These various headers gives the server fine-grained control over configuring their CORS behavior.

So in your example, a malicious server could set those headers, but the headers wouldn't do anything on their own. A client would need to make a conscious decision in order to send a request to the malicious server. In effect, the client itself would need to be malicious.




回答2:


You're misunderstanding the security issue.

The point of CORS is to prevent Javascript on other websites from reading sensitive information from your website.

Therefore, your website must explicitly state which origins are allowed to read its data.



来源:https://stackoverflow.com/questions/24018696/which-server-needs-to-return-access-control-allow-origin-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!