cross origin and cors

The browser same origin policy is a security mechanism which restricts how a document loaded from one origin can interact with another origin

For us engineers it means if you need to make (certain) kinds of requests to a different origin then you need to be aware of the restrictions and how to work around.

See mdn docs here for explanation of what is and is not considered same origin.

Some cross origin requests are allowed such as 

  • embedding: images (img), stylesheets, scripts, fonts, iframe
  • links, redirects and form submissions


So what to do if you need to make cross origin requests which are restricted?

You need to use CORS (cross origin resource sharing). It is a http header mechanism which allows a server to configure origins (other than it's own) for which it allows requests.

If mydomain.com wants to make a http request to yourdomain.com then unless yourdomain.com configures CORS that request will fail.

Some http requests are considered "simple" e.g. Get and POST using limited header. These just need the target domain to allow cors requests. This can be done by the target server responding with header Access-Control-Allow-Origin: which can allow all "*" or select origins.

For non "simple" requests CORS will include a "preflight" check using http Options and special handshake.


note: CSRF can be used on the server to protect against access from disallowed actors.

"But calling the api on postman works, why not in the browser?" - yes that's because postman does not have the restrictions a browser has.

How do I handle in my web app?

  • say you have an app which needs to make http fetch request to a non origin and the non origin urls are different in qa and production
  • the app needs to proxy the api calls when running locally e.g. to the QA endpoints (webpack dev server allows you to setup proxies)
  • tje app needs to detect the environment (qa vs production) and target the appropriate non origin domain for qa or production
  • the non origin target server needs to allow cors requests (either allow all or from this origin)




Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more