Cross-Origin Resource Sharing (CORS) is a mechanism that allows resources (such as fonts, JavaScript, or AJAX requests) on a web page to be requested from a different domain than the one from which the resource originated. In other words, it enables web browsers to make requests across different domains.
Cross-Origin Resource Sharing (CORS)
By default, web browsers enforce a policy called the Same-Origin Policy, which restricts web pages from making requests to a different domain.
This security measure is in place to prevent malicious scripts from accessing sensitive data or performing unauthorized actions on behalf of the user.
CORS introduces a set of HTTP headers that allow servers to specify which origins are allowed to access their resources.
When a web page makes a cross-origin request, the browser sends an initial "preflight" request (using the HTTP OPTIONS method) to check if the server permits the actual request.
The server responds with appropriate CORS headers indicating whether the request is allowed or denied.
- Access-Control-Allow-Origin : Specifies the allowed origin(s) that can access the resource. It can be a specific origin, "*", or null (for requests from file:// URLs).
- Access-Control-Allow-Methods: Specifies the allowed HTTP methods for the actual request.
- Access-Control-Allow-Headers: Specifies the allowed headers for the actual request.
- Access-Control-Allow-Credentials: Indicates whether the actual request can include credentials (e.g., cookies, HTTP authentication) or not.
- Access-Control-Max-Age: Specifies how long the preflight response can be cached (in seconds).
When the server includes appropriate CORS headers in the response, the browser determines if the requested resource can be accessed by the web page based on those headers. If the headers permit the request, the browser allows the cross-origin access and the web page can interact with the requested resource.
CORS is an essential mechanism for enabling controlled cross-origin data sharing between web applications while maintaining security. It provides a standardized way for servers to specify their access policies, allowing client-side code running in web browsers to securely consume data and services from different domains.