Same Origin and CORS

Much of this is taken from the same origin and CORS articles at Mozilla, which provide much more information.

  1. A web page is built from many resources of different types: HTML, images, CSS, Javascript, etc. These are loaded from various locations.
  2. The base page loads these resources by URL, which means they could be anywhere.
  3. In classic web, this no big deal. But as the web is used for more things, this starts to create problems. One in particular is called a Cross-Site Request Forgery (CSRF).
    1. When a browser sends a request, all the cookies go along, so the the request essentially carries all current credentials.
    2. When a user is logged in to an account, any request from the browser will be treated as authorized.
    3. If Joe, while logged into site bank, visits some other site, not-bank, the relevant cookies are not sent to not-bank.
    4. But some Javascript on the non-bank page could build and send a request to bank.
    5. Bill, who either works at non-bank, or just hacked it, could then use Javascript to construct and send a request to bank that transfers $1000 from Joe to Bill.
    6. Since it's going to bank, it brings all the cookies and bank will treat it as authorized.
  4. To help limit this, browsers implement a Same-Origin Policy.
    1. A page (or other resource) is limited in its access to resources from different origins.
    2. The Javascript at origin not-bank would be forbidden to fetch a page with origin bank.
    3. An origin is the triple of protocol, port and host. (But not path.)
    4. Not as simple as it sounds.
      1. Pages created by Javascript generally inherit the origin of the script.
      2. Special URLs like about:, and file: URLs present some subtleties.
      3. Javascript can adjust its own origin by removing subdomains (so foobar.fred.com can become fred.com. (Apparently, this capability is deprecated.)
    5. Different types of requests are restricted differently.
      1. Cross-origin linking, including form submission, and embedding (e.g., images) is generally allowed.
      2. XMLHttpRequest (and the newer Fetch) are restricted. (The origin of the request is the origin of the Javascript, wherever it's data actually came from.)
      3. Full rules are complicated.
  5. Sometimes you want to allow a cross-origin transaction which the policy would forbid. Third-party services: authentication, payment, etc.
  6. Cross-Origin Resource Sharing (CORS) is an HTTP extension to control such access.
    1. In the simplest form, the foreign server sends the header Access-Control-Allow-Origin: * to permit the loading by the foreign site.
    2. Alternatively, the header may give a list of allowed origins.
    3. There is much more to this, which I mostly don't understand just now.