CORS: Cross-Origin Resource Sharing
Links: practical guide for constructing CORS request, mozilla instructions for CORS, preflight requests, using CORS tutorial
9 flashcards · Programming Languages · by lakesare
What's a same-origin policy?
Restricts how a script loaded from one origin can interact with a resource from another origin. It is a critical security mechanism for isolating potentially malicious documents.
What's an origin in same-origin policy?
A combination of protocol host port For "http://www.example.com/dir/page.html":
In what cases same-origin policy doesn't apply?
Images with the <img> tag, as long as the file type matches expected image formats. Media files with the <video> and <audio> tags as long as the file type matches expected media formats. JavaScript with the <script src="..."></script> tag. CSS with the <link rel="stylesheet" href="..."> tag.
Name 2 methods to avoid same-origin policy.
JSONP (JSON with padding) CORS Before the adoption of CORS, there was no way to avoid same-origin policy. Script tags don't have this issue though, and JSONP is based on it. Now CORS is advised due to it being more secure.
How did JSONP work?
For each new JSONP request, new <script> tag is added. After the element is injected, browser performs an HTTP GET on the src URL, retrieving the content. <script src="hi.com/Users/3?callback=parseResponse"> </script> And received payload is: parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});. Padding refers to browser return a function call instead of JSON.
How to find docs for fetch?
Fetch doesn't have standard docs, it implements 'interfaces'. The only necessary argument is: fetch(url) It returns response interface, and accepts a request as a 2nd argument.
What are 3 possible values for: fetch('/hi', { credentials }) Default?
omit: never send cookies. same-origin: send cookies if same origin. include: always send cookies, even for cross-origin calls. Default is omit.
What are possible values for: fetch('/hi', { mode }) Default?
same-origin: raise an error if url is another origin. no-cors: method must be HEAD, GET, POST. Js can't access Response. cors: allows cross-origin requests if server is set up for this. Default is no-cors.
What exactly does this error mean: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access.
We set up server to respond with the header: Access-Control-Allow-Origin: * AND we set up fronted to request with: fetch(url, { mode: 'cors', credentials: 'include' }) For security reasons browser doesn't allow this, now we need to set Access-Control-Allow-Origin: http://localhost:5000 instead.