Search code examples
javascriptcorssame-origin-policy

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


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]


Solution

  • 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.