What is CORS and how is it used

Let’s say we wanted to provide a service at http://orlandotemp.net/temp that responds to AJAX GET requests from the external site example.com with a JSON object containing the current temperature in Orlando, FL. All we need to do to enable this cross-domain resource sharing is ensure that the requests from example.cominclude the header:

Origin: example.com

(which they will by default), and that our responses include the header:

Access-Control-Allow-Origin: example.com

This is the basic mechanism of CORS: requests include headers indicating what is being requested, and responses include headers indicating what is allowed. If there is agreement, the cross-domain request is permitted.

In this example, since we are only dealing with GET requests for public information, we can open our service up to be used by any external domain by responding with the header:

Access-Control-Allow-Origin: *

As you can see, the sometimes annoying configuration of Access-Control headers provides fine-grained control over exceptions to cross-origin constraints.

Preflight

Sending a GET request along with an access token in order to fetch private information is certainly powerful, but it’s the type of thing we do regularly when typing a URL into a browser’s address bar. GET requests should have zero risk of resulting in the destruction or manipulation of server-side data. Other types of requests—PUTDELETE, certain POSTs, etc.—are inherently riskier, and therefore require an additional security measure when using CORS.

Instead of making an AJAX request directly and checking the relevant headers, a web browser making more sensitive requests will first send a “preflight” request: a request using the OPTIONS method that essentially asks permission before sending the more sensitive request upon confirmation.

For example, if one were to send an AJAX DELETE request to another domain, the browser would first send an OPTIONS request with the header:

Access-Control-Request-Method: DELETE

If the response contained the header:

Access-Control-Allow-Methods: DELETE

along with an appropriate Access-Control-Allow-Origin header, then the desired DELETE request would be sent.

Posted in: Web

Leave a Reply

Your email address will not be published. Required fields are marked *