Cross-origin resource sharing (CORS) is a mechanism based on HTTP headers that permits restricted access to a resource with a different domain.
The browser restricts the web page of different origin, this mechanism is called same origin policy. For example, https://www.demo.com/abc.html and https://www.demo.com/xyz.html these two urls are of the same origin. Consider the following urls:
- https://www.demo.org – .Different domain. This URLs end with .org
- http://www.demo.com – Different scheme: In this URL you can see that the protocol is ‘http://’ not ‘https://’. The ‘s’ (secure) is missing.
- https://www.demo.com:1234/abc.html – Different port number. The port number is a communication endpoint. In this URL the port no is 1234.
These kinds of different origins are blocked by browser security.
But sometimes the web page has to request some of the resources from different origins. In such cases you can use the Cross Origin Resource Sharing (CORS) as it allows the server to relax the same origin policy.
Same Origin Policy
The same origin policy will restrict the website interacting with the resource from different domains.It helps prevent personal data from being stolen from one website to another.
How CORS Works
To make CORS Work you will have to add the new HTTP header that describes which origins allow you to read the information. To enable the CORS on the server, you have to add an additional header (Access-Control-Allow-Origin) to whitelist the urls.
For example, if your API server is hosted in https://api.demo.com/customer and the CORS is configured in it, when you access the API from https://www.sample.com webpage it will send a response with the following header:
Access-Control-Allow-Origin: https://www.sample.com
The following image illustrates how CORS works. The client sends the request to the server API and the server API sends back the response with the header Access-Control-Allow-Origin: https://www.sample.com.
Also, you can use wildcard character(*), which means that the resource can be accessed by any origin.
Access-Control-Allow-Origin: *
Preflight Request
The preflight request is a small request sent by the browser before the original request. This will give the server an idea about the actual request.The server will then announce whether or not to send a request to the browser. The preflight request contains metadata about the HTTP method and additional request header. The server inspects the metadata and decides whether or not to send the request.
Note:
If the CORS policy is not properly configured, then it leads to cross-domain based attacks.