CORS restrict Access-Control-Allow-Origin to certain domains.
Hey,
so I have an api and some of the routes should only be accessible by specific domains. Of course I have oAuth implemented, so the request needs to provide an access token, but I figured it might make sense to restrict the routes to certain domains.
I could of course check the Origin header and compare it to an array of domains, but I am not sure this is correct.
How would I implement something like this? Does it even make sense? Is there any good, not so theoretical resource on CORS? All I found was basically for allowing all domains Access-Control-Allow-Origin: * but this is not what I need.
You have to remember CORS is not access control system and you should not expect all cross-origin requests will have pre-flights that could be handled by middleware. For so-called 'simple' methods with so-called 'simple' headers request will be made without pre-flight. Thus you can not restrict such requests with CORS and should use other means. For example method 'GET' without any headers or with only 'simple' headers will not have pre-flight request so disabling it will not restrict access to resource(s).
Also folks who use tools like curl or similar can send you any header so you can't rely on that data as they are not protected by cryptography. You should implement 'usual' protection with Bearer/Basic/etc Authentication and authorization.
If you are OK that your protection works only for browsers CORS is totally fine (however you should remember about 'simple' methods and headers).