Why isn't my CORS configuration causing incoming requests to be filtered? How can I make it only accept requests from a specific origin?

走远了吗. 提交于 2019-11-28 11:49:12

CORS configuration won’t prevent the server from accepting requests based on the value of the Origin request header. You can’t do that just through CORS configuration.

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

Actual enforcement of CORS restrictions is done only by browsers. It’s not enforced by servers.

The way the protocol works is that regardless of what CORS configuration you make on the server side, the server continues to accept requests from all clients and origins it otherwise would—and so all clients from all origins continue to get responses from the server just as they otherwise would.

So even when 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 your frontend code running at a particular origin if the server the request was sent to opts-in to allowing the request by responding with an Access-Control-Allow-Origin header that allows that origin.

So for any requests with an Origin request header matching https://foreign.domain, the configuration snippet in the question should cause browsers to emit a message on the client side saying http://localhost:3000/api/v1/bodies.json can’t be loaded because there’s no Access-Control-Allow-Origin response header in the response (because your configuration causes the server to only send that header in responses to your whitelisted origins).

But that’s all you can do through CORS. You can’t prevent the server side from accepting and responding to requests from particular origins just by doing any CORS configuration on the server side. If you want to do that, you need to do it using something other than just CORS configuration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!