How to implement CORS (Access-Control-Allow-Origin) correctly?

6.7k Views Asked by At

I would like to access an third party resource (on another domain) via XML HTTP Requests (XHR, AJAX).

I setup CORS as follows (on both sides - target and origin):

Access-Control-Allow-Origin: http://www.example.com, https://www.example.com, http://www.example.org, https://www.example.org
Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS

Chrome, Firefox and Internet Explorer reject the XHR to https://www.example.org/foo when calling it on http://www.example.com/bar.

Most detailed error message is from Firefox:

XMLHttpRequest cannot load https://www.example.org/foo. The 'Access-Control-Allow-Origin' header contains multiple values 'http://www.example.com, https://www.example.com, http://www.example.org, https://www.example.org', but only one is allowed. Origin 'http://www.example.com' is therefore not allowed access.

That error confuses me extremely. It's like "Hey, you are A and want to talk to B but B only accept A, B. So you cannot talk to B". WTF?

How to implement CORS (Access-Control-Allow-Origin) correctly?

1

There are 1 best solutions below

1
On BEST ANSWER

Access-Control-Allow-Origin only accepts * or a single origin.

If you want to support multiple origins but not all of them, then you must:

  1. look at the Origin request header
  2. check if it is on your list of acceptable origins
  3. put it in the Access-Control-Allow-Origin response header