Open 6thfdwp opened 3 years ago
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
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/
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.Access-Control-Allow-Origin
*
if the request can be sent from any origin to the serverAccess-Control-Allow-Methods
A comma-separated HTTP headers that are allowed to talk to the server
Access-Control-Allow-Headers
A comma-separated list of the custom headers that are allowed to be sent
Access-Control-Allow-Max-Age
The maximum duration that the response to the preflight request can be cached before another call is made
The general flow looks like:
Browser checks if the request is a 'simple' request, a request is simple when:
User-Agent
)Content-Type
: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 theOPTIONS
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.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 customAuthorization
headers, is this allowed?"If the server responded with
Access-Control-*
headers covering those requested inOPTIONS
, the actual POST request will be sent.We can see how it looks in Chrome Network