1

A fellow developer and I were experiencing a weird issue with our application in the past couple of days. Specifically, he's writing the API and I'm writing the web front end. Since the UI runs from a different port, we have to setup CORS in the application so that the UI could make requests into the API.

I'll not go into great detail but this is the first project where I've had to heavily engage CORS. Specifically, our problem was related to the UI code sending JSON data as the request body and specifying in the header a content type of application/json. Since this isn't an acceptable content type within CORS, the preflight rejected the request.

At the time neither of us were aware of preflight requests and I had assumed my fetch(...) calls were modifying my headers and dropping my data. After finally digging into the mechanics of CORS, we were able to discern that the problem was with the preflight request receiving a response stating that my content-type wasn't accepted.

after we fixed our issue, I couldn't help but wonder what was the purpose of the preflight check. Specifically, this doesn't benefit to browser/UI. You should an error when you make a request that isn't accepted by CORS and the response from the server can relay this specifics of why your request isn't needed. In other words, you could skip a preflight check and just rely on the response from the server to dictate whether the request is correct, and this saves the browser from making two requests for the single call.

Preflight checks also don't benefit the server. The server should reject any request that doesn't match the CORS requirements, regardless of whether a preflight call has been made or not.

So, what's the point of the preflight? Why is it proper for the browser to make to calls, instead of one, when the default allowable CORS header properties are different than what's being requested by the client?

1 Answer 1

3

In other words, you could skip a preflight check and just rely on the response from the server to dictate whether the request is correct, and this saves the browser from making two requests for the single call.

That would assume that the server is properly validating the request in the first place. The problem is that many servers don't which is the reason CSRF works.

Traditionally it was impossible to do cross-site requests doing JavaScript at all. CORS allows to relax this restriction. But CORS was designed in a way that it will not reduce inadvertently the security. Server side code which simply relied on the fact that XHR could never be done cross-site should not be accidentally become insecure. That's why with all but simple cross-site requests done with JavaScript the browser first checks that the server will explicitly allow a cross-site request by sending a preflight request before doing the real request it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .