CORS (Cross Origin Resource Sharing) is a standard for accessing Web resources on different domains. CORS is a mechanism that allows web scripts to interact more openly with content outside of the original domain, leading to better integration between web services.
Before going into the details of how CORS works, it is important to understand what HTTP headers are.
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP header fields are components of the header section of request and response messages in the Hypertext Transfer Protocol (HTTP). They Allows the client and the server to pass additional information with the request or the response.
Headers (according to their contexts)
- General Header: Header applying to both request and response. This header has no relation to data eventually transmitted.
- Request Header: Contains information about the resources to be fetched.
- Response Header: Contains information about response like its location or about server itself.
- Entity Header: Contains information about body of entity like its content length etc.
Now when we know what HTTP header and CORS means, its time to understand the need of CORS and for this we must be aware of Same-Origin Policy.
To prevent websites from tampering with each other, web browsers implemented a security measure known as the same-origin policy. 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 (defined as a combination of URL scheme, host-name and port number).
Cross-Origin Resource Sharing (CORS) is a technique for relaxing the same-origin policy, CORS adds HTTP headers which instruct web browsers on how to use and manage cross-domain content.
How CORS works?
- The user’s browser creates a connection to the second domain, adding an “Origin” HTTP header to the request which contains the first domain.
- The second domain replies with an “Allow-Content-Origin” HTTP header which lists the domains allowed to make CORS requests. A ‘*’ wildcard allows all domains to make request. [ ACAO : Access Control Allow Origin]
- If the first domain is allowed to make the request, the second domain responds with the requested content.
This is all about what CORS is, why it is needed and how it works!
Stay Connected to learn more.