DEV Community

Cover image for Cors Workflow

Posted on

Cors Workflow

What is Cors and it's workflow

Cross-Origin Resource Sharing (CORS) is a security mechanism implemented by web browsers to manage requests made to a different domain than the one serving the web page. It aims to mitigate the risks of cross-site request forgery (CSRF) and other cross-site attacks, thereby enhancing the security of web applications.

Here's a detailed breakdown of the CORS workflow and its significance:

Initiation of a Request from a Web Page:
The process begins when a web page (origin A) attempts to access a resource hosted on a different origin (origin B).
"Simple" or "Non-Simple" Request Check:
Before sending the actual request, the browser determines whether it's a "simple" or "non-simple" request. Simple requests typically involve methods like GET, POST, or HEAD and a limited set of headers. Non-simple requests trigger a preflight request.
Preflight Request (for Non-Simple Requests):
For non-simple requests, the browser sends an OPTIONS request (preflight request) to the target origin (origin B). This request includes headers specifying details of the actual request it intends to make.
Server Response to Preflight Request:
Upon receiving the preflight request, the server (origin B) responds. If the server allows the origin to access the resource, it responds with a set of headers indicating permission. The browser rejects the actual request if the server fails to provide the required headers or if they don't match the request details.
Sending the Actual Request:
With the preflight request completed (either successfully or determined unnecessary), the browser proceeds to send the actual request to origin B, including any necessary headers, credentials, or data.
Server Response to the Actual Request:
Upon receiving the request, the server processes it and sends a response. Along with the response, the server includes appropriate CORS-related headers.
Browser Enforcement:
Finally, the browser checks the CORS headers in the response. If they meet the expected criteria, the browser provides the response to the web page's JavaScript. Otherwise, it blocks access to the response and logs a CORS error in the console.
CORS provides servers with control over which origins can access their resources, thereby enhancing security. Browsers enforce CORS rules to safeguard users from potential security threats. Despite introducing additional complexity, CORS serves as an effective security measure to facilitate safe cross-origin data sharing.

Top comments (0)