Wednesday, October 28, 2020

CORS Theory

Wikipedia explains CORS as:

"The CORS standard describes new HTTP headers which provide browsers with a way to request remote URLs only when they have permission."

along with the visual explanation of "Path of an XMLHttpRequest(XHR) through CORS." as below:

 

--------------------------------------------------------------------------------------------------------------------------------------------------

Browsers use preflight OPTIONS request for CORS verification. A preflight request is issued by the Browser itself when:

  1. Conditions in above diagram are met or
  2. Request has a Stream Data
  3. Request is from different Origin

OPTIONS request is browser's way of asking/telling server that the next subsequent request will have file stream data or is going to be from a different origin, etc. and asking Server to respond if this kind of request is supported by the server or not. If server supports it then it responds with a HTTP 200 OK with the Access-Control-* headers to indicate WHAT exactly is allowed by the server.

Courtesy (for above sequence diagram):  https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Some of the CORS headers and their sample values are as follows:

const corsOrigin = 'https://some.other.origin:4444/relative/path/goes/here';
res.header('Access-Control-Allow-Origin', corsOrigin);
res.header('Access-Control-Allow-Methods', 'POST,OPTIONS');
res.header('Access-Control-Allow-Headers',
'Authorization,Content-Type,Accept,Referer,Origin,X-Requested-With');
res.header('Access-Control-Allow-Credentials', true);

What constitutes a cross-domain:

  1. Different protocol
  2. Different domain
  3. Different port


No comments: