What is the expected response to an invalid CORS request?

I just want to add to the Monsur's answer. There is one another behaviour(the one that is currently in use by S3):

  1. To only send CORS response headers when they match the request's Origin. Otherwise, not send any CORS headers at all and let your browser, or any other client, decide for yourself.

At least this is how it works for me.

Also, when it comes to Java, it's common to send 403. That Java link is quite old, but the de-facto standard in Java, Spring, approach is the same. See my reference here.


Yes, I realize I'm answering my own question, but here it goes anyway. I did some research into this and it seems like behavior falls into two camps:

1) Return an error if the CORS request is invalid. This is the route taken by the Java CORS filter project. This library returns

  • 400 Bad Request for requests that don't conform to the spec
  • 403 Forbidden for invalid origins or headers.
  • 405 Method Not Allow for invalid methods

2) Return CORS headers in the response and let the browser sort out the access details. This seems to be the far more common approach, and is used by the APIs for Amazon S3, SoundCloud, FourSquare and Spotify (the latter two APIs benefit from only supporting simple CORS requests). In this case, the server doesn't do any error checking, and just returns the CORS headers for the supported origin, method and headers. The browser still makes the request, but if the CORS response headers don't match the user's request, the browser withholds the response from the user.

Each of these methods has their pros and cons. Method #1 is more closely aligned to the CORS spec, but provides no useful debugging information to the user.

Method #2 provides more insight into what the supported methods and headers are. It is also easier to implement, since the server is returning the same response headers regardless of the request headers. However this comes at the expense of actually executing the request on the server-side, even though the browser will block the response from the user. This may not be desirable for a method with side-effects, such as POST, PUT or DELETE and highlights the fact that CORS should not be used as an authentication mechanism.

(Note that my research above is by no means exhaustive. It was tough to see the true behavior for many APIs, since they either required auth, or blocked the request at a different level for some other error, such as an unsupported method.)

Tags:

Cors