Will CORS policy prevent resource access from non-browser requests?

However, does this prevent Http requests from a CURL, or other native applications/web-servers (ie. a request written and run via PHP) from successfully retrieving data from that resource?

No, CORS config won’t prevent non-browser stuff from successfully retrieving your resources.

The same-origin policy is enforced only by browsers. It’s not enforced by servers. (And CORS is a way to relax the same-origin policy.) It’s not the case that if there’s some lack of any CORS details in a request, servers somehow block requests, or refuse to send responses.

Instead when you configure CORS support on a server, all that the server does differently is just to send the Access-Control-Allow-Origin header and other CORS response headers.

The way the protocol works is, regardless of what CORS configuration you make on the server side, all clients—even browsers—continue to get responses from the server as they normally would. But the difference is, curl or other native apps or backend server-side programming environments such as PHP will not prevent your client code from accessing the response if it doesn’t include the Access-Control-Allow-Origin response header. But browsers will.

Specifically, even if you see an error in your browser devtools that a cross-origin request from your frontend JavaScript code failed, you’ll still be able to see the response in browser devtools.

But just because your browser can see the response doesn’t mean the browser will expose it to your frontend JavaScript code. Browsers only expose responses from cross-origin requests to frontend code running at a particular origin if the server the request went to opts-in to allowing the request, by responding with an Access-Control-Allow-Origin header allowing that origin.

But browsers are the only clients which do that. Browsers are the only clients that implement the same-origin policy and the CORS protocol. curl or other native applications or HTTP client requests made server-side runtimes such as PHP don’t implement the CORS protocol, so you can’t block requests from them by doing any CORS configuration on the server side.

So If you want to block requests to a resource from non-browser clients, you need to do it using something other than CORS configuration.

Leave a Comment