What is the same-origin policy?
As per wiki In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.
Cross-Origin Resource Sharing enables web clients to make HTTP requests to servers hosted on different origins. CORS is a unique web technology in that it has both a server-side and a client-side component. The server-side component configures which types of cross-origin requests are allowed, while the client-side component controls how cross-origin requests are made.
CORS is a unique web technology in that it has both a server-side and a client-side component. The server-side component configures which types of cross-origin requests are allowed, while the client-side component controls how cross-origin requests are made.
So if the browsers enforce the same-origin policy, how does CORS work? The magic lies in the request and response headers. The browser and the server use HTTP headers to communicate how cross-origin requests should behave. Using the response headers, the server can indicate which clients can access the API, which HTTP methods or HTTP headers are allowed, and whether cookies are allowed in the request.
We can break down the steps to process a CORS request and response as follows.
- The CORS request is initiated.
- The browser includes additional HTTP headers on the request before sending the request to the server.
- The server includes HTTP headers in the response that indicates whether the request is allowed.
- If the request is allowed, the browser sends the response to the client code.
If the headers returned by the server don’t exist or aren’t what the browser expects, the response is rejected and the client can’t view the response.
Let’s create a simple example to call two different APIs using JQuery and see the response.
Save the above code in an HTML file and run it in chrome. When we use the World Time API as a URL for our get request, it is executed successfully and we can see the detailed response in the browser as below.
But, if we comment on the world time API URL and remove comments from the yahoo URL and re-run the file, we wouldn’t see any response in the browser. If you check the browser console you will see an error message with details as :
“Access to XMLHttpRequest at ‘https://in.yahoo.com/’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
Here you can see the world time API application allowing a request from a different origin but yahoo did not.
Happy Learning !!