I'm still trying to wrap my head around the mechanics of CORS (Cross-Origin Resource Sharing). From what I understand, when browsers enforce the Same-Origin Policy (SOP), it can restrict legitimate cross-site requests. CORS was introduced to alleviate some of these restrictions by allowing servers to specify who can access their resources through specific headers in the response. However, I'm confused about some scenarios. For example, if a bank website has an endpoint like /sendmoney, and a malicious site (let's call it evil.com) tries to make a request to that endpoint, will the bank's backend process that request? My understanding is that the browser will block evil.com from seeing the response, but that doesn't prevent it from hitting the endpoint in the first place. Is CORS simply there to restrict access to the response rather than preventing the request itself? Also, I've read about CSRF tokens, and I feel like those are the real protection needed here, while CORS doesn't fully solve the issue.
5 Answers
The backend will respond to any request it receives, but CORS is essentially a way to instruct the browser on how to handle cross-origin requests. So if evil.com tries to make a request to bank.com, the browser typically won't let it through unless bank.com explicitly permits it. If a browser ignored CORS, then the request would go through just fine.
For GET requests, browsers use the CORS headers from the response to determine whether it should allow users to see the data. However, for POST requests, there's typically an initial OPTIONS request to check those headers before the actual POST is made. If the CORS headers are not set properly, the POST won’t ever be sent.
A helpful way to think about CORS is to imagine the interactions between the server, the browser, and the requesting site. The server doesn’t care who is asking for the data, whereas the browser is protective and only reveals responses if the originating site has permissions defined through CORS headers. This adds a layer of security against unwanted data access.
CORS does block certain requests completely. For example, if a POST request with application/json content is sent to a different domain, the browser won't send that request unless the server allows it through CORS headers in response to an OPTIONS preflight. However, form submissions have always been allowed to cross domains without CORS restrictions since it predates CORS, which is why CSRF tokens are so important for form submissions to enhance security.
You're right! CORS primarily prevents evil.com from viewing responses. There’s also the idea of a preflight request that checks if the origin is authorized before the actual request is made, but relying solely on it isn't secure. That's why CSRF tokens are vital for protecting against those risks.
Just a heads up, though, a POST request isn't always preceded by an OPTIONS call if it qualifies as a "simple request." So it's a bit more complex than that.