Why does CORS block custom headers by default?

2019-02-18 10:37发布

问题:

I assume that the default blocking of custom headers in cors requests is to prevent some kind of attack.

Is that assumption correct? If so, what's the attack?


from https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method.

回答1:

The cross-origin restrictions in browsers are designed to not cause servers to permit scripted cross-origin XHR/Fetch requests to do anything by default more than what browsers already allow for requests for images, scripts, and stylesheets made using the img, script, and link elements.

When in the HTML markup for a document or application at origin A you put an img, script, or link element that embeds an image, script, or stylesheet from origin B, there’s no way you can set custom headers on the request for that image, script, or stylesheet from origin B.

Therefore, the default browser behavior for scripted cross-origin XHR/Fetch requests is designed to match the same behavior/restrictions inherent in requests initiated by img/script/link markup.

The principle at work here is to not break any assumptions made by somebody in their server-side code that they won’t receive requests from documents/applications running in a browser that include custom headers or that do anything else somebody can’t do using img/script/link.

But the purpose of the CORS protocol is to allow servers to opt-in to something less strict than that default behavior. So the specific way they can opt in to less-strict behavior for request headers is, they can choose to send Access-Control-Allow-Headers and use that to tailor/tune/control exactly what request headers they want to allow scripted cross-origin XHR/Fetch requests to make.

But if they don’t opt-in by choosing to send Access-Control-Allow-Headers, then they can be confident that browsers aren’t going to allow scripted cross-origin XHR/Fetch requests from frontend JavaScript code to do something surprising/unexpected they have not opted-in to.

And to be clear, it’s not ”CORS” that’s imposing the default restrictions. Instead those restrictions are just part of the default same-origin policy that browsers follow, and as documented in places like https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy and https://en.wikipedia.org/wiki/Same-origin_policy. So CORS is just a means for allowing servers to choose when they want to ask browsers to use less-strict restrictions for particular resources.