CORS (Cross-Origin Resource Sharing)

CORS (Cross-Origin Resource Sharing)

Exploring CORS and its importance

What is CORS: Cross-Origin Resource Sharing?

This is a configuration that allows web pages to make requests to servers in a different domain from the one that served them. Normally, browsers enforce Same-Origin Policy (SOP), which restricts how a document or script loaded from one origin can interact with resources from another origin. This policy blocks cross-origin requests by default unless explicitly allowed via mechanisms like CORS. To allow such resource sharing, the destination server has to have CORS enabled to grant the cross-origin request. In an S3 context, CORS settings are managed via a bucket’s CORS configuration where specific origins, headers, and methods can be allowed.

Example: Suppose a front-end JavaScript application is hosted on origin-bucket.s3.amazonaws.com and it tries to fetch data from https://cross-bucket.s3.amazonaws.com/data.json

When the browser makes the request, it adds an Origin Header. The Origin header indicates the origin (protocol, domain, and port) of the request that is making a cross-origin call. In return, the responding server adds the Access-Control-Allow-Origin header to the response indicating which origins are allowed to access the resource. This header MUST either match the origin header on the request or be set to * (wildcard), allowing any origin, but not for requests with credentials like cookies. Otherwise, a mismatch in the two prevents the requested resource data from being shared.

If CORS is not allowed on the responding server, you get an error like:

Access to fetch 'cross-bucket.s3.amazonaws.com/data.json' from origin 'origin-bucket.s3.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

“Preflight” in CORS

For non-standard HTTP methods (e.g PUT, DELETE), requests with custom headers or requests that send credentials like cookies or Authorization headers, the browser first sends a Preflight request to the server to check if the actual request is allowed. This request uses the OPTIONS method and the server responds to this with the allowed HTTP methods for a resource. This ensures that the browser can now send the allowed request methods without any CORS errors

All in all, CORS is important because:

It helps prevent unauthorized requests from malicious sites.

It ensures APIs can only be accessed by the allowed domains.

It facilitates controlled resource sharing across domains.