We need to keep our API server security with CORS restriction :
All the solutions I found tell me to allow all origin :*
, but this would be a big security failure for our API.
You don’t explain why you’ve determined it would be a security failure or why you need to have a restrictive CORS policy at all. But unless (1) the API server is running in an intranet or behind some other kind of firewall, and (2) access to the resources is otherwise restricted only by IP auth, then you don’t gain anything from using a restrictive CORS policy. To quote the spec:
Basic safe CORS protocol setup
For resources where data is protected through IP authentication or a firewall (unfortunately relatively common still), using the CORS protocol is unsafe. (This is the reason why the CORS protocol had to be invented.)
However, otherwise using the following header is safe:
Access-Control-Allow-Origin: *
Even if a resource exposes additional information based on cookie or HTTP authentication, using the above header will not reveal it. It will share the resource with APIs such as
XMLHttpRequest
, much like it is already shared withcurl
andwget
.Thus in other words, if a resource cannot be accessed from a random device connected to the web using
curl
andwget
the aforementioned header is not to be included. If it can be accessed however, it is perfectly fine to do so.
And the author of the Fetch/CORS spec goes into a bit more detail in a related blog posting:
It is completely safe to augment any resource with
Access-Control-Allow-Origin: *
as long as the resource is not part of an intranet (behind a firewall). In other words, a URL you can fetch from a server on the internet usingwget
orcurl
. For your basic web site this encompasses all resources on the site. TheAccess-Control-Allow-Origin
header (part of CORS) tells the browser the resource can be shared.Even if the resource includes confidential information based on cookies or HTTP authentication data in the request, including the header and sharing the resource is still safe, since the browser will make the request without any cookies or HTTP authentication data. And if the browser did make the request with cookies or HTTP authentication data, it would never share the resource because that would require an additional header,
Access-Control-Allow-Credentials
, and a different value for the aforementioned header.So go ahead and safely share your public data with other applications!