Cross-Origin Resource Sharing

Cross-Origin Resource Sharing:

Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries.
If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access.
Usually web browsers forbids cross-domain requests, due the same origin security policy.
Cross-origin resource sharing (CORS) is a technique that allow servers to serve resources to permitted origin domains
by adding HTTP headers to the server who are respected from web browsers.

Web Server Settings:

You can send the response header with PHP like,

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: origin, x-requested-with, content-type");
header("Access-Control-Allow-Methods: GET, OPTIONS");

Or Set Header using Web Server. I am using Apache Web Server for this tutorial.

To add the CORS authorization to the header using Apache, simply add headers inside either
the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config
(usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file.

<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "GET, OPTIONS"
</IfModule>

Adding “*” in header will make your url public. Any one can request data from that url.

If you want to restrict it to one/more domains as follows

1) Only one domain “http://search.mysite.com/”.

Header add Access-Control-Allow-Origin "http://search.mysite.com/"

2) Multiple sub-domain

SetEnvIf Origin "^(.*\.mysite\.com)$" ORIGIN_SUB_DOMAIN=$1
Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN

3) Multiple Other domain.

SetEnvIf Origin "^http(s)?://(.+\.)?(mysite\.org|mysite\.com)$" ORIGIN_DOMAIN=$0
Header always set Access-Control-Allow-Origin %{ORIGIN_DOMAIN}e env=ORIGIN_DOMAIN

File can be found at following location,
1) /etc/apache2/sites-available/mysite.conf
2) /etc/apache2/apache2.conf
3) /var/www/mywebsite/.htaccess

To ensure that your changes are correct, it is strongly reccomended that you use
#apachectl -t

to check your configuration changes for errors. After this passes, you may need to reload Apache to make sure your changes are applied by running the command

#sudo service apache2 reload
or
#apachectl -k graceful

Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it’s enabled by run
#a2enmod headers

Note: you can also use add rather than set, but be aware that add can add the header multiple times, so it’s likely safer to use set.

Web Browser/Client Code:

Include following scripts,

<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js">
</script><script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

and add following code at the end of your page.


$("#autocomplete").autocomplete({
autoFocus: true,
minLength: 3,
source: function (request, response) {
$.ajax({
url: "http://www.mysite.com/url",
data: 'query=' + request.term,
crossDomain: true,
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function (data, status) {
if (data.content.error != null) {
alert(data.content.error);
} else {
var x;
var item = [];
for (x in data.content.data) {
item[x] = data.content.data[x].url;
}
response(item);
}
},
error: function (err) {
alert(err);
}
});
},
select: function (event, ui) {
val = $("#autocomplete").val();
window.open(ui.item.value);
$("#autocomplete").val(val);
return false;
}
});

If you want to prevent Apache from executing your code when the browser sends a HTTP OPTIONS Prefight request , returning 200 OK, Add following rewrite rule in .htaccess,

<IfModule mod_rewrite.c>
RewriteEngine On
# Always return 200 OK for OPTIONS method.
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>

and use “always set” to overwrite cors headers in vhost section,

<VirtualHost *:80>
ServerName search.mysite.com
DocumentRoot /var/www/mysite/
<Directory /var/www/mysite>
AllowOverride All
Options -Indexes
</Directory>
<IfModule mod_headers.c>
SetEnvIf Origin "^(.*\.stockopedia\.com)$" ORIGIN_SUB_DOMAIN=$1
Header always set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
Header always set Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always set Access-Control-Allow-Methods "GET, OPTIONS"
</IfModule>
</VirtualHost>

More details can be found at,

http://enable-cors.org/index.html

http://www.html5rocks.com/en/tutorials/cors/

Thanks.

This entry was posted in Client-side Scripting. and tagged , , . Bookmark the permalink.

Leave a Reply