Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Access-Control-Allow-Origin CORS header required when doing a preflight request?

We are seeing the well-known CORS error on our site:

XMLHttpRequest cannot load https://my-site.com/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://my-other-site.com' is therefore not allowed access.

The thing is, the Access-Control-Allow-Origin is set correctly on the preflight request...

OPTIONS https://my-site.com/api HTTP/1.1
Host: my-site.com
Access-Control-Request-Method: POST
Origin: https://my-other-site.com
Access-Control-Request-Headers: my-custom-header, accept, content-type
Accept: */*
Referer: https://my-other-site.com/
...other stuff...


HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://my-other-site.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: my-custom-header, accept, content-type
Access-Control-Expose-Headers: my-custom-header
...other stuff...

...however, it's not set on the subsequent request.

POST https://my-site.com/api HTTP/1.1
Host: my-site.com
Accept: */*
My-Custom-Header: abcd123
Origin: https://my-other-site.com
Referer: https://my-other-site.com/
...other stuff...


HTTP/1.1 200 OK
My-Custom-Header: abcd123
...other stuff...

I don't understand the problem. According to everything I've read online, if we use a preflight request, we shouldn't need to add CORS headers for the actual request. However, that's clearly not the case.

All of the examples here and here include an Access-Control-Allow-Origin header in the actual response, but don't include any of the other "required" CORS headers. When we add that one header to our actual response, the error goes away.


So my question is, is the Access-Control-Allow-Origin header actually required in both requests? Where is that stated? And why is that true?

like image 701
BlueRaja - Danny Pflughoeft Avatar asked Dec 08 '14 21:12

BlueRaja - Danny Pflughoeft


1 Answers

Yes, it appears both responses should include the necessary CORS headers.

In both the Simple Cross-Origin Request and the Cross-Origin Request with Preflight, the "actual request" follows the same behavior, checking for CORS headers regardless of the preflight (step 1 and step 3, respectively).

  1. [...] Apply the make a request steps and observe the request rules below while making the request.

    • ... (snipped: 3xx codes, aborts, and network errors)

    • Otherwise

      Perform a resource sharing check. [...]

The resource sharing check algorithm for a given resource is as follows:

  1. If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.

  2. [...]

The preflight request only prevents the "actual request" from beginning.

like image 124
Jonathan Lonowski Avatar answered Sep 25 '22 18:09

Jonathan Lonowski