6thfdwp / learning-thoughts

Record and Reflect
2 stars 0 forks source link

Understand CORS #1

Open 6thfdwp opened 3 years ago

6thfdwp commented 3 years ago

What

CORS (Cross-Origin Resource Sharing) is a security relaxation (based on HTTP-header) for the default browser security mechanism same-origin policy, which it does not allow requests to a different host other than the one JS is running within.

Why

As in What, it is to allow requests to go to a different host for some legit scenarios as commonly seen in the SPA setup.
It is also good to know why same-origin needed, because otherwise some malicious page (hackerdomain.com) can be sent to user, and issues a request to yourdomain.com right from user's browser. If yourdomain uses session cookie to store some sensitive data (e.g authed token), hackerdomain.com could just use it along with the request and get the response or perform some actions that should not be publicly available.

How it works

We need to configure the server to respond with certain headers Access-Control-*, so browser knows it can continue the request and consume the response.

The general flow looks like:

Browser checks if the request is a 'simple' request, a request is simple when:

If it is a simple request, it will be directly sent as normal and Allow-Control-* headers will be checked when response comes back.
Otherwise the browser will send a preflight request with OPTIONS http method. This is used to determine what the server is supporting, if the response of the OPTIONS showing not allowed, the following request won't be sent at all. It's like domain needs to be approved before even sending a request.

image

It basically says: "I want to make a POST request to https://api.domain.com" from https://app.domain.com with Content-Type, Accept and custom Authorization headers, is this allowed?"
If the server responded with Access-Control-* headers covering those requested in OPTIONS, the actual POST request will be sent.

We can see how it looks in Chrome Network image

6thfdwp commented 3 years ago

References

MDN CORS Doc Complete Guide to CORS
Implication of CORS
What requests use CORS.

It is worth noting there will be some performance overhead when request is preflighted, since it is an extra round trip to your server before the real request is sent, caching can be applied to reduce it. Reduce preflight overhead

6thfdwp commented 3 years ago

Some other real security cases (XSS) that is interesting to be reviewed:
XSS via a spoofed React Element

Dan wrote a post about it and showed what's the fix React did https://overreacted.io/why-do-react-elements-have-typeof-property/