Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-origin resource sharing (CORS) concept

I have a question on the concept cross domain JavaScript.

There is server(ex amazon.com) where in only selected domains can use their web-service. So definitely, if I try to use their service, from my local, I cannot. I got this on my console

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://football20.myfantasyleague.com/2014/export?TYPE=rosters&L=52761&W=&JSON=0. This can be fixed by moving the resource to the same domain or enabling CORS.

PS: I used jquery cross domain way too, but didnt work.

But if some domain who is among the selected ones, to use Amazon's webservice, has a JavaScript, which if we include in our html, it works.

<script src="http://example.com"></script>

They have a method to get response by Ajax.

My questions are:

  1. What happens when we refer a JavaScript file from an internet url. Do we have a local copy running on our machine?
  2. Is the httpRequest created, will have a request source as my domain or the xyz.
like image 437
Sashi Kant Avatar asked Aug 14 '14 14:08

Sashi Kant


People also ask

What is CORS cross-origin resource sharing policy?

CORS is a mechanism that uses additional HTTP header to inform a browser to allow a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

What is CORS simple explanation?

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.

Why do we use CORS?

CORS is a security protocol implemented by browsers that allow us to access resources from a different origin. CORS requests are of three types: Simple , Preflight , and Request with Credentials . Simple requests are used to perform safe operations like an HTTP GET method.

What is CORS and how do you deal with it?

CORS is an abbreviation for Cross-Origin Response Sharing. It is what allows the website on one URL to request data from a different URL, and it frustrates both the frontend and backend devs alike. You might've added an image URL only to end up with something like this.


2 Answers

Important note up front: If the server at the other end doesn't enable it, there's nothing you can do in your client-side code that will allow a cross-origin ajax request.

Let me give you a background before answering your question:

Same-Origin Security Policy

Simply put, same-origin security policy makes sure that scripts from one origin may not fetch content from other origins. Now to explain you the concept of origin, let me quote part of the Wikipedia article of Same-Origin Security Policy:

The following table gives an overview of typical outcomes for checks against the URL "http://www.example.com/dir/page.html".

Compared URL                                             Outcome  Reason
-------------------------------------------------------  -------  ----------------------
http://www.example.com/dir/page2.html                    Success  Same protocol and host
http://www.example.com/dir2/other.html                   Success  Same protocol and host
http://username:[email protected]/dir2/other.html Success  Same protocol and host
http://www.example.com:81/dir/other.html                 Failure  Same protocol and host but different port
https://www.example.com/dir/other.html                   Failure  Different protocol
http://en.example.com/dir/other.html                     Failure  Different host
http://example.com/dir/other.html                        Failure  Different host (exact match required)
http://v2.www.example.com/dir/other.html                 Failure  Different host (exact match required)
http://www.example.com:80/dir/other.html                 Depends  Port explicit. Depends on implementation in browser.

Unlike other browsers, Internet Explorer does not include the port in the calculation of the origin, using the Security Zone in its place.

So, for example, your JavaScript cannot download anything from (aka, make an HTTP request to) a web server other than the server it originated from. This is exactly why you cannot make XmlHttpRequests (aka AJAX) to other domains.


CORS is one way the server at the other end (not the client code in the browser) can relax the same-origin policy.

An Oversimplified Description about Cross Origin Resource Sharing (CORS).

The CORS standard works by adding new HTTP headers which allow servers to serve resources to permitted origin domains. Browsers support these headers and respect the restrictions they establish.

Example: Say your site is http://my-cool-site.com and, you have a third party API at domain http://third-party-site.com, which you can access via AJAX.

And let's assume that a page from your server my-cool-site.com made a request to third-party-site.com. Normally, users browser will decline AJAX calls to any other site other than your own domain/subdomain per the Same-Origin Security Policy. But if the browser and the third party server supports CORS, following things happen:

  • Browser will send and Origin HTTP header to third-party-site.com

    Origin: http://my-cool-site.com
    
  • If the third party server accepts requests from your domain, it will respond with an Access-Control-Allow-Origin HTTP header:

    Access-Control-Allow-Origin: http://my-cool-site.com
    
  • To allow all domains, third party server can send this header:

    Access-Control-Allow-Origin: *
    
  • If your site is not allowed, browser will throw an error.

If the client's have fairly modern browsers that support CORS, and your third party server supports CORS as well, CORS can be useful to you.

In some obsolete browsers (IE8, for instance), you have to use a Microsoft-specific XDomainRequest object instead of XMLHttpRequest to make a call that will work correctly with CORS; this outdated now, all modern browsers (including from Microsoft) handle CORS in XMLHttpRequest instead. But if you need to support obsolete browsers, this page describes it:

To make a CORS request you simply use XMLHttpRequest in Firefox 3.5+, Safari 4+ and Chrome and XDomainRequest object in IE8+. When using XMLHttpRequest object, if the browser sees that you are trying to make a cross-domain request it will seamlessly trigger CORS behaviour.

Here is a javascript function that helps you create a cross browser CORS object.

function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        // XHR has 'withCredentials' property only if it supports CORS
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){ // if IE use XDR
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

Again, that's only necessary for obsolete browsers.


The above reasons are why you cannot use Amazon's web services from your script. And Amazon server will only allow downloading their JavaScript files to pages served from selected domains.

To answer your numbered questions:

    • The file will be downloaded by the browser if it is in the same origin.
    • If it is not in the same origin, the file will be downloaded if a CORS request succeeds.
    • Or otherwise, downloading the script will fail.
    • If the download succeeds, the content of the JavaScript file will be loaded to browser's memory, interpreted, and executed.
  1. See description on CORS to understand.

like image 164
sampathsris Avatar answered Sep 30 '22 11:09

sampathsris


CORS is a setting that must be modified on the server. It allows resources on a webpage to be requested by an external domain. Simply changing your code on the client will not change the functionality of CORS.

The reason you can access a page from within a "script" tag, is because tags are treated differently than all other data for cross origin requests. In the old days, you could "hack" CORS onto your system using JSONP which stores JSON data inside of HTML tags.

To enable CORS in Apache:

First find your httpd.conf by typing

ps -ef | grep apache

Which will give you the location of Apache. Once you have found that type:

 <apache-location> -V

Which will return the exact location of your httpd.conf like such:

 -D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Now you need to go to httpd.conf and type "/" to search for <directory>. Once you find the tag, right after it type:

Header set Access-Control-Allow-Origin "*"

Save the file and confirm the syntax is correct by running:

apachectl -t

If that checks out, run the graceful restart command:

apachectl -k graceful

Once the server restarts, your files should now be accessible via external scripts.

If you where not able to save the config due to an error, try exiting your editor and typing:

sudo chmod 755 httpd.conf

This gives the owner full access to the configuration file but everyone else can only read an execute it (http://en.wikipedia.org/wiki/Chmod).

To test these changes, on an external server create a new index.html file and load it up with the following:

<!doctype html>
<html>
    <head>
    <title>TEST</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <!-- Insert Scripts & CSS Here -->
    <link rel="stylesheet" type="text/css" href="http://d1e24pw9mnwsl8.cloudfront.net/c/bootstrap/css/bootstrap.min.css">
    </head>

    <body>

        <script>
        jQuery.get('yourwebsite.com/file.csv', function(data) {
        document.write(data);
        });
        </script>

    </body>

</html>

The resulting output should mirror the live data feed at yourwebsite.com/file.csv

If loading up that html page shows no ouput, press f12 on firefox to open the developer's console. Most likely you will see an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at yourwebsite.com/file.csv. This can be fixed by moving the resource to the same domain or enabling CORS.

This means either a) your httpd.conf was not configured correctly/did not save, or b) you forgot to restart the web server.

like image 33
Andrew Avatar answered Sep 30 '22 13:09

Andrew