CORS-Sharing
Tags: Mti, Technical

1.Introducing CORS

What’s CORS

CORS is Cross Origin Resource Sharing. It’s a policy allow sharing resources between different domains. Its request called from front-end to others domain back-end

Why CORS

because of the same-origin policy for the browser security feature that restricts how documents and scripts on one origin can interact with resources on another origin.

A bit knowledge about same origin policy

Same-origin: same protocol, port(if it’s specified), host. Example : https://www.domainname.com/demo Same-origin with https://www.domainname.com/practice

But http://www.domainame.com/demo is not same-origin because http # https

But http://www.domainame.com/demo is not same-origin because http # https Same-origin policy example

- We have one iframe embed in one site but JavaScript code and the Document Object Model (DOM) of this site cannot access the content of its iframe unless they are of the same origin

- Cookies cannot be sent to a page with a different origin

- XmlHttpRequest to other domain but cannot get the response

What requests use CORS

This cross-origin sharing standard can enable cross-site HTTP requests for :

XmlHttpRequest or Fetch APIs

Web Fonts (for cross-domain font usage in @font-face within CSS)@font-face {font-family: ‘OpenSans’; src: url(‘https://fonts-face-domain.com/OpenSans.woff2') format(‘woff2’);}

WebGL textures

Images/video frames drawn to a canvas using drawImage()

const canvas = document.getElementById(‘canvas’);

const ctx = canvas.getContext(‘2d’);

const image = “https://image-source.jpg”;

image.addEventListener(‘load’, e => {

ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);

});

const canvas = document.getElementById(‘canvas’); const ctx = canvas.getContext(‘2d’); const image = “https://image-source.jpg”; image.addEventListener(‘load’, e => { ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); CSS Shapes from images

img {shape-outside: url(../images/star-shape1.png);}

CORS example

An example of a cross-origin request:

the front-end JavaScript code served from https://domain-a.com uses XmlHttpRequest to make a request for https://domain-b.com/data.json

Or https://domain-a.com want to get font, canvas image from https://domain-b.com

Note: Generally, embedding a cross-origin resource is permitted, while reading a cross-origin resource is blocked

Benefit of CORS

Opens an API to a wider audience

Puts servers in charge of how CORS behaves

Allows flexible configuration options

Makes it easy for client developers to use

Reduces maintenance overhead for server developers

2.How to use CORS

a. Config server

The server need setting what header will be response for client

Access-Control-Allow-Origin: <origin> | *

Access-Control-Allow-Credentials: true/false, mean can exposed to client Http cookies and Http Authentication information

Access-Control-Expose-Headers: this setting lets a server whitelist headers that Javascript (such as getResponseHeader()) in browsers are allowed to access.

Access-Control-Allow-Methods: POST, GET, OPTIONS

Access-Control-Allow-Headers: Custom-header, Content-Type, …

Access-Control-Max-Age: 86400(indicates how long the results of a preflight request can be cached in seconds)

b. Send CORS request

The request sent from client, will have these headers

Origin: domain-origin can be null or URI, and always sent to server

Access-Control-Request-Method: Http method used in this request

Access-Control-Request-Headers: what header will used for this request

CORS has 2 type of request

Simple requests: it’s a normal request has many condition mark it safe to send

example : allowed methods are get, head, post; CORS-safelisted request-header such as accept, accept-language; content-type are : application/x-www-form-urlencoded, multipart/form-data, text/plain

example : allowed methods are get, head, post; CORS-safelisted request-header such as accept, accept-language; content-type are : application/x-www-form-urlencoded, multipart/form-data, text/plain Preflighted requests: unlike Simple for “preflighted” requests the browser first sends an HTTP request using the OPTIONS method to the resource on the other origin, in order to determine if the actual request is safe to send

The flow of CORS request

C. Browser compatibility

Internet Explorer 8 and 9 expose CORS via the XDomainRequest object, but have a full implementation in IE 10

Each browser has its behaves to CORS different

3. Debugging CORS requests

a. Using browser develop tool

Most browser have its develop tool and they are also support many features. In this section, we just focus to debugging and network monitor for debug CORS

Let check Google Chrome — develop console as image below

Google Chrome — network monitor

b. Monitoring network traffic software

Using Wireshark: this is a tool that monitors and logs all network traffic passing through your computer. The network traffic isn’t limited to HTTP requests, but it includes all network traffic, including TCP and UDP traffic

Using Charles/Fiddler: this is another packet analyzer. It is easier to use than Wireshark. Fiddler supports a lot of other features, such as web debugging, web session manipulation, performance testing, and security testing

c. Using curl to simulate CORS requests

When building a new CORS implementation, it’s often useful to craft HTTP requests to the server and observe the results. One way to do this is to create a web page with an XMLHttpRequest that performs exactly the request you need

Example we can use these command to execute XmlHttp request from CURL

“curl — verbose -H “Origin: http://localhost:9000" http://localhost:8000/api/lytc”

4. Fix CORS issue

Regardless of what tools you use to solve the issue, the steps to solving CORS errors are the same

Capture a snapshot of the request and response headers

2. Compare the headers to see if and where there is a mismatch

3. Fix the issue by either

Updating the client to send the correct headers

Updating the server to allow the client headers

5. References