CORS in Azure

Cross-Origin Resource Sharing (CORS) defines a policy-driven approach for controlling how web applications make cross-domain requests. This is in contrast to the long-established single-origin policy (SOP), which says that URLs in JavaScript (and elsewhere) can only refer to the origin URL of the page. The advantage of CORS is that it allows a web app to pull resources (e.g., data and other features) from multiple websites onto one page without having to construct proxies or use other workarounds. CORS defines a contract between the client-side browser and the server application as well as an algorithm that is followed to enable server applications to opt in to allowing cross-origin requests.

Finding Your Origin

A typical web application consists of a rich browser-based client (using HTML5, JavaScript, and CSS3), served up from a web server application (such as with ASP.NET or MVC 3 in an Azure Web role) and integrating data from various Representational State Transfer (REST) services. From the perspective of the browser, there are two scenarios for how the web app gets its data from the services: same-origin and cross-origin (aka cross-domain).

In the same-origin scenario, the services are hosted within the same web server application that delivered the web page, or they may exist externally and be called from the web server application logic with their resultant data integrated in the web server application’s response. In either case, from the browser’s perspective they are being reached from the same server — the same origin.¬†When services are accessed with different hostnames, protocols, or ports, the request is considered cross-origin. This is very common for websites that use third-party services for their data, where the browser-based client calls the service directly and the domain used to access the service is different from the domain that delivered the web page. The subtle issue here is that browsers enforce an SOP whereby such cross-domain requests are not allowed, in order to protect the browser from malicious code loaded from the external domain.

This is not an issue specific to web applications hosted on Azure, but if you are doing any amount of web application development on Azure you will undoubtedly encounter the SOP. In fact, Azure introduces additional scenarios where cross-origin resource access is required. Naturally it is best to architect your Azure-hosted solution with the SOP in mind, rather than encounter SOP and have to make drastic changes to your web application when you least expect it.

Copyright © All Rights Reserved - C# Learners