Cross Domain AJAX Request - Pktasks.com Your Source for Crypto News and Job Opportunities"

Post Top Ad

Cross Domain AJAX Request

A common problem for developers is a browser to refuse access to a remote resource. Usually, this happens when you execute AJAX cross domain request using jQuery Ajax interface, Fetch API, or plain XMLHttpRequest. As result is that the AJAX request is not performed and data are not retrieved.

Figure 1. The same-origin policy restriction in effect

SAME-ORIGIN POLICY

This is a security policy who defines the rules of how a web page can access an external resource (e.g. fonts, AJAX requests). Under the same-origin policy, web browsers do not permit a web page to access resources who origin differ than that of the current page. The origin is considered to be different when the scheme, hostname or port of the resource do not match that of the page. Overcoming the limitations of same-origin security policy is possible using a technique called Cross-origin resource sharing or simply CORS.

CROSS-ORIGIN RESOURCE SHARING

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin.
Figure 2. Cross domain ajax request
When you do a cross-origin request, the browser sends Origin header with the current domain value.
Origin: http://zinoui.com
When the server receives the request, check whether the origin header is within the allowed list, and sends a response with Access-Control-Allow-Origin
Access-Control-Allow-Origin: http://zinoui.com
If you want to allow access for all, use a wildcard '*'
Access-Control-Allow-Origin: *

AJAX CROSS DOMAIN REQUEST

1. Simple request
A simple cross-domain request is one that:
  • Does not send custom headers (such as X-PINGOTHER, etc.)
  • Only uses GET, POST or HEAD request methods
This is how the simple cross domain ajax request should looks like:
<script type="text/javascript">
// jQuery cross domain ajax
$
.get("http://www.example.org/ajax.php").done(function (data) {
console
.log(data);
});

// using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr
.open("GET", "http://www.example.org/ajax.php", true);
xhr
.onload = function () {
console
.log(xhr.responseText);
};
xhr
.send();

// using the Fetch API
fetch
("http://www.example.org/ajax.php").then(function (response) {
return response.json();
}).then(function (json) {
console
.log(json);
});
</script>
2. Preflighted requests
Setting custom headers to XHR triggers a preflight request. With simple words this mean that preflight request first send an HTTP request by the OPTIONS method to the resource on the remote domain, to make sure that the request is safe to send. According W3C for non same origin requests using the HTTP GET method a preflight request is made when headers other than Accept and Accept-Language are set.
<script type="text/javascript">
// jQuery preflight request
$
.ajax({
type
: "GET",
headers
: {"X-My-Custom-Header": "some value"},
url
: "http://www.example.org/ajax.php"
}).done(function (data) {
console
.log(data);
});

// XMLHttpRequest preflight request
var xhr = new XMLHttpRequest();
xhr
.open("GET", "http://www.example.org/ajax.php", true);
xhr
.setRequestHeader("X-My-Custom-Header", "some value");
xhr
.onload = function () {
console
.log(xhr.responseText);
};
xhr
.send();

// Fetch preflight request
var myHeaders = new Headers();
myHeaders
.append("X-My-Custom-Header", "some value");
fetch
("http://www.example.org/ajax.php", {
headers
: myHeaders
}).then(function (response) {
return response.json();
}).then(function (json) {
console
.log(json);
});
</script>
3. Request with credentials
By default, for non same origin request, browsers will not send credentials (such as HTTP Cookies, HTTP Authentication and client-side SSL certificates). A specific attribute has to be set on the XMLHttpRequest object when it is invoked.
<script type="text/javascript">
// jQuery CORS example
$
.ajax({
xhrFields
: {
withCredentials
: true
},
type
: "GET",
url
: "http://www.example.org/ajax.php"
}).done(function (data) {
console
.log(data);
});

// XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr
.open("GET", "http://www.example.org/ajax.php", true);
xhr
.withCredentials = true;
xhr
.onload = function () {
console
.log(xhr.responseText);
};
xhr
.send();

// Fetch with credentials
fetch
("http://www.example.org/ajax.php", {
credentials
: "include"
}).then(function (response) {
return response.json();
}).then(function (json) {
console
.log(json);
});
</script>
4. The Response
Let's see how the server response should look like:
<?php
// http://www.example.org/ajax.php
if (!isset($_SERVER['HTTP_ORIGIN'])) {
// This is not cross-domain request
exit;
}

$wildcard
= FALSE; // Set $wildcard to TRUE if you do not plan to check or limit the domains
$credentials
= FALSE; // Set $credentials to TRUE if expects credential requests (Cookies, Authentication, SSL certificates)
$allowedOrigins
= array('http://zinoui.com', 'http://jsfiddle.net');
if (!in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins) && !$wildcard) {
// Origin is not allowed
exit;
}
$origin
= $wildcard && !$credentials ? '*' : $_SERVER['HTTP_ORIGIN'];

header
("Access-Control-Allow-Origin: " . $origin);
if ($credentials) {
header
("Access-Control-Allow-Credentials: true");
}
header
("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header
("Access-Control-Allow-Headers: Origin");
header
('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies

// Handling the Preflight
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}

// Response
header
("Content-Type: application/json; charset=utf-8");
echo json_encode
(array('status' => 'OK'));
?>
Few notes:
  • A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
  • Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) removed support for using the withCredentials attributes when performing synchronous requests.

BROWSER SUPPORT

Chrome 3+, Firefox 3.5+, IE 10+, Opera 12+, Safari 4+

No comments:

Post a Comment

Post Top Ad