Cross-origin resource sharing

Last updated

Cross-origin resource sharing (CORS) is a mechanism that allows a web page to access restricted resources from a server on a domain different than the domain that served the web page.

Contents

A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. [1] Certain "cross-domain" requests, notably Ajax requests, are forbidden by default by the same-origin security policy. CORS defines a way in which a browser and server can interact to determine whether it is safe to allow the cross-origin request. [2] It allows for more freedom and functionality than purely same-origin requests, but is more secure than simply allowing all cross-origin requests.

The specification for CORS is included as part of the WHATWG's Fetch Living Standard. [3] This specification describes how CORS is currently implemented in browsers. [4] An earlier specification was published as a W3C Recommendation. [5]

Technical overview

Path of an XMLHttpRequest (XHR) through CORS. Flowchart showing Simple and Preflight XHR.svg
Path of an XMLHttpRequest (XHR) through CORS.

For HTTP requests made from JavaScript that can't be made by using a <form> tag pointing to another domain or containing non-safelisted headers, the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests. [6]

Simple request example

Suppose a user visits http://www.example.com and the page attempts a cross-origin request to fetch data from http://service.example.com. A CORS-compatible browser will attempt to make a cross-origin request to service.example.com as follows.

  1. The browser sends the GET request with an extra Origin HTTP header to service.example.com containing the domain that served the parent page:
    Origin: http://www.example.com
  2. The server at service.example.com sends one of these three responses:
    • The requested data along with an Access-Control-Allow-Origin (ACAO) header in its response indicating the requests from the origin are allowed. For example in this case it should be:
      Access-Control-Allow-Origin: http://www.example.com
    • The requested data along with an Access-Control-Allow-Origin (ACAO) header with a wildcard indicating that the requests from all domains are allowed:
      Access-Control-Allow-Origin: *
    • An error page if the server does not allow a cross-origin request [7]

A wildcard same-origin policy is appropriate when a page or API response is intended to be accessible to any code on any site. A freely available web font on a public hosting service like Google Fonts is an example.

A wildcard same-origin policy is also widely and appropriately used in the object-capability model, where pages have unguessable URLs and are meant to be accessible to anyone who knows the secret.[ original research? ]

The value of "*" is special in that it does not allow requests to supply credentials, meaning that it does not allow HTTP authentication, client-side SSL certificates, or cookies to be sent in the cross-domain request. [8]

Note that in the CORS architecture, the Access-Control-Allow-Origin header is being set by the external web service (service.example.com), not the original web application server (www.example.com). Here, service.example.com uses CORS to permit the browser to authorize www.example.com to make requests to service.example.com.

If a site specifies the header "Access-Control-Allow-Credentials:true", third-party sites may be able to carry out privileged actions and retrieve sensitive information.

Preflight example

When performing certain types of cross-domain Ajax requests, modern browsers that support CORS will initiate an extra "preflight" request to determine whether they have permission to perform the action. Cross-origin requests are preflighted this way because they may have implications to user data.

OPTIONS / Host: service.example.com Origin: http://www.example.com Access-Control-Request-Method: PUT 

If service.example.com is willing to accept the action, it may respond with the following headers:

Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Methods: PUT 

The browser will then make the actual request. If service.example.com does not accept cross-site requests from this origin then it will respond with error to the OPTIONS request and the browser will not make the actual request.

Headers

The HTTP headers that relate to CORS are:

Request headers

Response headers

Browser support

CORS is supported by all browsers based on the following layout engines:

History

Cross-origin support was originally proposed by Matt Oshry, Brad Porter, and Michael Bodell of Tellme Networks in March 2004 for inclusion in VoiceXML 2.1 [20] to allow safe cross-origin data requests by VoiceXML browsers. The mechanism was deemed general in nature and not specific to VoiceXML and was subsequently separated into an implementation NOTE. [21] The WebApps Working Group of the W3C with participation from the major browser vendors began to formalize the NOTE into a W3C Working Draft on track toward formal W3C Recommendation status.

In May 2006 the first W3C Working Draft was submitted. [22] In March 2009 the draft was renamed to "Cross-Origin Resource Sharing" [23] and in January 2014 it was accepted as a W3C Recommendation. [24]

CORS vs JSONP

CORS can be used as a modern alternative to the JSONP pattern. The benefits of CORS are:

The main advantage of JSONP was its ability to work on legacy browsers which predate CORS support (Opera Mini and Internet Explorer 9 and earlier). CORS is now supported by most modern web browsers. [25]

See also

Related Research Articles

<span class="mw-page-title-main">Document Object Model</span> Convention for representing and interacting with objects in HTML, XHTML, and XML documents

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML or XML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

<span class="mw-page-title-main">HTTP</span> Application protocol for distributed, collaborative, hypermedia information systems

The Hypertext Transfer Protocol (HTTP) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, where hypertext documents include hyperlinks to other resources that the user can easily access, for example by a mouse click or by tapping the screen in a web browser.

XForms is an XML format used for collecting inputs from web forms. XForms was designed to be the next generation of HTML / XHTML forms, but is generic enough that it can also be used in a standalone manner or with presentation languages other than XHTML to describe a user interface and a set of common data manipulation tasks.

In computing, the User-Agent header is an HTTP header intended to identify the user agent responsible for making a given HTTP request. Whereas the character sequence User-Agent comprises the name of the header itself, the header value that a given user agent uses to identify itself is colloquially known as its user agent string. The user agent for the operator of a computer used to access the Web has encoded within the rules that govern its behavior the knowledge of how to negotiate its half of a request-response transaction; the user agent thus plays the role of the client in a client–server system. Often considered useful in networks is the ability to identify and distinguish the software facilitating a network session. For this reason, the User-Agent HTTP header exists to identify the client software to the responding server.

XML Linking Language, or XLink, is an XML markup language and W3C specification that provides methods for creating internal and external links within XML documents, and associating metadata with those links.

In the context of an HTTP transaction, basic access authentication is a method for an HTTP user agent to provide a user name and password when making a request. In basic HTTP authentication, a request contains a header field in the form of Authorization: Basic <credentials>, where <credentials> is the Base64 encoding of ID and password joined by a single colon :.

<span class="mw-page-title-main">XMLHttpRequest</span> Javascript class to transfer data between a web browser and a web server

XMLHttpRequest (XHR) is a JavaScript class containing methods to asynchronously transmit HTTP requests from a web browser to a web server. The methods allow a browser-based application to make a fine-grained server call and store the results in XMLHttpRequest's responseText attribute. The XMLHttpRequest class is a component of Ajax programming. Prior to Ajax, an HTML form needed to be completely sent to the server followed by a complete browser page refresh.

Ajax is a set of web development techniques that uses various web technologies on the client-side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and, by extension, web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly utilize JSON instead of XML.

In computer hypertext, a URI fragment is a string of characters that refers to a resource that is subordinate to another, primary resource. The primary resource is identified by a Uniform Resource Identifier (URI), and the fragment identifier points to the subordinate resource.

<span class="mw-page-title-main">Same-origin policy</span> Security measure for client-side scripting

In computing, the same-origin policy (SOP) is a concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model (DOM).

<span class="mw-page-title-main">HTTP referer</span> HTTP header field

In HTTP, "Referer" is an optional HTTP header field that identifies the address of the web page, from which the resource has been requested. By checking the referrer, the server providing the new web page can see where the request originated.

<span class="mw-page-title-main">HTML5</span> Fifth and previous version of hypertext markup language

HTML5 is a markup language used for structuring and presenting hypertext documents on the World Wide Web. It was the fifth and final major HTML version that is now a retired World Wide Web Consortium (W3C) recommendation. The current specification is known as the HTML Living Standard. It is maintained by the Web Hypertext Application Technology Working Group (WHATWG), a consortium of the major browser vendors.

Web storage, sometimes known as DOM storage, is a standard JavaScript API provided by web browsers. It enables websites to store persistent data on users' devices similar to cookies, but with much larger capacity and no information sent in HTTP headers. There are two main web storage types: local storage and session storage, behaving similarly to persistent cookies and session cookies respectively. Web Storage is standardized by the World Wide Web Consortium (W3C) and WHATWG, and is supported by all major browsers.

<span class="mw-page-title-main">WebSocket</span> Computer network protocol

WebSocket is a computer communications protocol, providing simultaneous two-way communication channels over a single Transmission Control Protocol (TCP) connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. The current specification allowing web applications to use this protocol is known as WebSockets. It is a living standard maintained by the WHATWG and a successor to The WebSocket API from the W3C.

Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website or web application where unauthorized commands are submitted from a user that the web application trusts. There are many ways in which a malicious website can transmit such commands; specially-crafted image tags, hidden forms, and JavaScript fetch or XMLHttpRequests, for example, can all work without the user's interaction or even knowledge. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser. In a CSRF attack, an innocent end user is tricked by an attacker into submitting a web request that they did not intend. This may cause actions to be performed on the website that can include inadvertent client or server data leakage, change of session state, or manipulation of an end user's account.

The cache manifest in HTML5 was a software storage feature which provided the ability to access a web application even without a network connection. It became part of the W3C Recommendation on 28 October 2014.

Content Security Policy (CSP) is a computer security standard introduced to prevent cross-site scripting (XSS), clickjacking and other code injection attacks resulting from execution of malicious content in the trusted web page context. It is a Candidate Recommendation of the W3C working group on Web Application Security, widely supported by modern web browsers. CSP provides a standard method for website owners to declare approved origins of content that browsers should be allowed to load on that website—covered types are JavaScript, CSS, HTML frames, web workers, fonts, images, embeddable objects such as Java applets, ActiveX, audio and video files, and other HTML5 features.

HTML5 Audio is a subject of the HTML5 specification, incorporating audio input, playback, and synthesis, as well as in the browser. iOS

WebXR Device API is a Web application programming interface (API) that describes support for accessing augmented reality and virtual reality devices, such as the HTC Vive, Oculus Rift, Oculus Quest, Google Cardboard, HoloLens, Apple Vision Pro, Magic Leap or Open Source Virtual Reality (OSVR), in a web browser. The WebXR Device API and related APIs are standards defined by W3C groups, the Immersive Web Community Group and Immersive Web Working Group. While the Community Group works on the proposals in the incubation period, the Working Group defines the final web specifications to be implemented by the browsers.

References

  1. "Same-origin policy / Cross-origin network access". MDN. 20 December 2023.
  2. 1 2 "Cross-domain Ajax with Cross-Origin Resource Sharing". NCZOnline. 25 May 2010. Retrieved 2012-07-05.
  3. "Fetch Living Standard".
  4. "WebAppSec Working Group Minutes".
  5. "Cross-Origin Resource Sharing".
  6. "Cross-Origin Resource Sharing (CORS) - HTTP | MDN". developer.mozilla.org. 10 May 2023. Retrieved 7 June 2023.
  7. "CORS errors - HTTP | MDN". developer.mozilla.org. 2023-05-10. Retrieved 2023-07-04.
  8. . W3.org. Retrieved on 2021-31-07.
  9. 1 2 "Blink". QuirksBlog. April 2013. Retrieved 4 April 2013.
  10. "Google going its own way, forking WebKit rendering engine". Ars Technica. April 2013. Retrieved 4 April 2013.
  11. "HTTP access control (CORS) - MDN". Developer.mozilla.org. Archived from the original on 2010-05-27. Retrieved 2012-07-05.
  12. "Gecko - MDN". Developer.mozilla.org. 2012-06-08. Archived from the original on 2012-08-03. Retrieved 2012-07-05.
  13. Tony Ross; Program Manager; Internet Explorer (2012-02-09). "CORS for XHR in IE10". MSDN. Retrieved 2012-12-14.
  14. "cross-site xmlhttprequest with CORS". MOZILLA. Retrieved 2012-09-05.
  15. David Honneffer, Documentation Specialist (2012-06-14). "12.00 for UNIX Changelog". Opera. Archived from the original on 2012-06-18. Retrieved 2012-07-05.
  16. David Honneffer, Documentation Specialist (2012-04-23). "Opera Software: Web specifications support in Opera Presto 2.10". Opera.com. Retrieved 2012-07-05.
  17. on July 6, 2009 by Arun Ranganathan (2009-07-06). "cross-site xmlhttprequest with CORS ✩ Mozilla Hacks – the Web developer blog". Hacks.mozilla.org. Retrieved 2012-07-05.{{cite web}}: CS1 maint: numeric names: authors list (link)
  18. "59940: Apple Safari WebKit Cross-Origin Resource Sharing Bypass". Osvdb.org. Archived from the original on 2012-07-19. Retrieved 2012-07-05.
  19. "Microsoft Edge deverloper's guide". 21 December 2023.
  20. "Voice Extensible Markup Language (VoiceXML) 2.1". W3.org. 2004-03-23. Retrieved 2012-07-05.
  21. "Authorizing Read Access to XML Content Using the <?access-control?> Processing Instruction 1.0". W3.org. Retrieved 2012-07-05.
  22. "Authorizing Read Access to XML Content Using the <?access-control?> Processing Instruction 1.0 W3C - Working Draft 17 May 2006". W3.org. Retrieved 17 August 2015.
  23. "Cross-Origin Resource Sharing - W3C Working Draft 17 March 2009". W3.org. Retrieved 17 August 2015.
  24. "Cross-Origin Resource Sharing - W3C Recommendation 16 January 2014". W3.org. Retrieved 17 August 2015.
  25. "When can I use... Cross Origin Resource Sharing". caniuse.com. Retrieved 2012-07-12.