79

I've been reading up on CORS and how it works, but I'm finding a lot of things confusing. For example, there are lots of details about things like

User Joe is using browser BrowserX to get data from site.com, which in turn sends a request to spot.com. To allow this, spot has special headers... yada yada yada

Without much background, I don't understand why websites wouldn't let requests from some places. I mean, they exist to serve responses to requests, don't they? Why would certain people's of requests not be allowed?

It would really appreciate a nice explanation (or a link to one) of the problem that CORS is made to solve.

So the question is,

What is the problem CORS is solving?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

3 Answers3

50

The default behavior of web browsers that initiate requests from a page via JavaScript (AKA AJAX) is that they follow the same-origin policy. This means that requests can only be made via AJAX to the same domain (or sub domain). Requests to an entirely different domain will fail.

This restriction exists because requests made at other domains by your browser would carry along your cookies which often means you'd be logged in to the other site. So, without same-origin, any site could host JavaScript that called logout on stackoverflow.com for example, and it would log you out. Now imagine the complications when we talk about social networks, banking sites, etc.

So, all browsers simply restrict script-based network calls to their own domain to make it simple and safe.

Site X at www.x.com cannot make AJAX requests to site Y at www.y.com, only to *.x.com

There are some known work-arounds in place (such as JSONP which doesn't include cookies in the request), but these are not a permanent solution.

CORS allows these cross-domain requests to happen, but only when each side opts into CORS support.

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 2
    Ah ok, so it's the browser that sets these rules. If so, then what's with the `Access-Control-Allow-Origin` on the server end? How would cross origin requests even get there if the browser won't allow it? – CodyBugstein Dec 08 '14 at 20:13
  • 1
    @Imray - see the CORS link in my answer. Newer browsers *support* CORS if the sites *opt in* to using it (via the header). – Haney Dec 08 '14 at 20:32
  • 2
    In MDN Access Cotrol doc, GET request with credentials are not preflighted. But if response headers doesn't include Access-Control-Allow-Credentials: true then response will not be available to the invoking client. If this behaviour same for POST (Simple POST request with credentials - Content Type may be form-data) request as well, there is risk that POST might change the server state though response may not be made available to client. Is this assumption correct? OR POST request with credentials pre-flighted? – Dhanaraj Durairaj Apr 18 '16 at 16:55
  • http://stackoverflow.com/questions/36613051/in-cors-are-post-request-with-credentials-pre-flighted – Dhanaraj Durairaj Apr 18 '16 at 16:56
  • The thing I really don't get though, is that if you make a GET or POST request, it won't get pre-flighted. So the server could still process the request. So in theory, couldn't you make a malicious request and it just doesn't show up to the client? – Cameron Mar 17 '22 at 22:36
  • Doesn't the `Same-Site=Strict` parameter for the `Set-Cookie` header obsolete all the CORS shenanigans? As far as I understand from the [docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) it prevents exactly what you are describing. – Balázs Édes Sep 19 '22 at 12:44
  • 1
    *requests can only be made via AJAX to the same domain (or sub domain). Requests to an entirely different domain will fail.* A [dangerous](https://jub0bs.com/posts/2022-02-08-cve-2022-21703-writeup/#bypassing-content-type-validation-and-avoiding-cors-preflight) oversimplification. Open your browser's Console on this very page and run `fetch('//example.com')`, then inspect the Network tab; you'll see that a `GET` request was indeed sent to `https://example.com`. – jub0bs Mar 18 '23 at 12:42
  • @BalázsÉdes The `SameSite` cookie attribute and CORS can be used in conjunction precisely because _site_ is broader than _origin_. More about this topic [elsewhere](https://jub0bs.com/posts/2022-08-04-scraping-the-bottom-of-the-cors-barrel-part1/#cors-vs-samesite). – jub0bs Mar 18 '23 at 12:45
  • @jub0bs did exactly that, and here's what my console gave me (chrome latest, win 10): _Access to fetch at 'https://example.com/' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled._ – Haney Mar 20 '23 at 21:03
  • @Haney Regardless of what you make of this error message, your request reached the server, as evidenced by what your browser's Network tab shows. The browser is only preventing your client (running in the context of Web origin `https://stackoverflow.com`) from reading the response to that request. – jub0bs Mar 20 '23 at 21:17
  • If you don't believe me, try `fetch('//some-server-you-control.com')` instead and then inspect that server's logs. – jub0bs Mar 20 '23 at 21:19
38

First, let's talk about the same origin policy. I'll quote from a previous answer of mine:

The same-origin policy was invented because it prevents code from one website from accessing credential-restricted content on another site. Ajax requests are by default sent with any auth cookies granted by the target site.

For example, suppose I accidentally load http://evil.com/, which sends a request for http://mail.google.com/. If the SOP were not in place, and I was signed into Gmail, the script at evil.com could see my inbox. If the site at evil.com wants to load mail.google.com without my cookies, it can just use a proxy server; the public contents of mail.google.com are not a secret (but the contents of mail.google.com when accessed with my cookies are a secret).

(Note that I've said "credential-restricted content", but it can also be topology-restricted content when a website is only visible to certain IP addresses.)

Sometimes, however, it's not evil.com trying to peek into your inbox. Sometimes, it's just a helpful website (say, http://goodsite.foo) trying to use a public API from another origin (say, http://api.example.com). The programmers who worked hard on api.example.com want all origins to access their site's contents freely. In that case, the API server at api.example.com can use CORS headers to allow goodsite.foo (or any other requesting origin) to access its API responses.

So, in sum, we assume by default that cross-origin access is a bad thing (think of someone trying to read your inbox), but there are cases where it's a good thing (think of a website trying to access a public API). CORS allows the good case to happen when the requested site wants it to happen.

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • So the browser still has to send some sort of request to all sites to see if they have `CORS` headers, right? If `evil.com` has a script to access my bank site, will my browser send a test request or something to check for those headers, while not attaching my cookies? – CodyBugstein Dec 08 '14 at 20:16
  • @Imray Yes, requests are performed on the network level; the results simply aren't shown to JavaScript if the CORS check fails. See my answer on [How does Access-Control-Allow-Origin header work?](http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work/10636765#10636765) (sorry to keep linking to my own stuff, but it's a question I've answered a few times before and the linked answers are (I hope) relevant to your questions) – apsillers Dec 08 '14 at 20:19
1

There are security and privacy reasons for not allowing requests from anywhere. If you visited my website, you wouldn't want my code to make requests to Facebook, reddit, your bank, eBay, etc. from your browser using your cookies, right? My site would then be able to make posts, read information, place orders, etc. on your behalf. Or on my behalf with your accounts.

Scott Saunders
  • 29,840
  • 14
  • 57
  • 64
  • If i'm visiting your site, you won't have access to my facebook cookies! you only have access to cookies for your own website, right!? – behz4d Mar 01 '22 at 09:15