Tunneling and proxy servers for Ajax and not just

Monday, December 10, 2007

Because of its ability to communicate with the server, the XMLHttpRequest object (XHR), which is used in technology Ajax (which stands for Asynchronous JavaScript and XML, which should be pronounced "egiacs" even if we Italians prefer "aiacs"), has a block of protection that prevents him from running outside requests to the domain in which it operates. This protection is necessary to prevent Javascript Injection (technical "injection" extremely dangerous code in order to break the system) of various types, with the ultimate aim of "breaking" the system.
This limit is now taken seriously and you are thinking, in some way to solve it - directly in the object XmlHttpRequest - without compromising security (see also: Third proposal for cross-site extensions to XMLHttpRequest).

Whatever the situation today is as follows:

XHR

JavaScript code that uses the XMLHttpRequest object (found on page yourWebApp.html) can only make requests to the domain miodominio.com, ie the domain where the Javascript code. No such scenario, then:

XHR

... will not work!

Furthermore, as shown on The Same Origin Policy to Mozilla:

[..] Mozilla considers two pages to have the same origin if the protocol, port (if given), and host are the same for both pages. To illustrated, this table gives examples of origin comparisons to the URL http://store.company.com/dir/page.html.

The Same Origin Policy

Is not just the domain to make things difficult. In addition consider that each browser has its own implementation of the XMLHttpRequest object and then his personal rules.
Anyway to solve this problem there are various techniques.

1. Proxy Server

This technique uses a server-side language to "trick", so to speak, the XHR object so as to create a tunnel between the XHR object and our external domain target. PHP, for example, is able to retrieve information from other domains in different ways, depending on the type of installation, and also set restrictions on our server. In the general case that we tend to do is this:

XHR

In short the XHR object communicates with our domain, where a page specially written retrieves information from an external domain. It then creates a proxy in PHP, that is a "page through" that retrieves information for us, restoring XHR object. One of the simplest proprosto proxy server is, for example, from Yahoo:

PHP:
  1. <? php
  2. / / PHP Proxy example for Yahoo! Web services.
  3. / / Responds to both HTTP GET and POST requests
  4. / /
  5. / / Author: Jason Levitt
  6. / / December 7th, 2005
  7. / /
  8. / / Allowed hostname (api.local and api.travel are also possible here)
  9. 'HOSTNAME' , 'http://search.yahooapis.com/' ) ; define ( 'HOSTNAME', 'http://search.yahooapis.com/');
  10. / / Get the REST call path from the AJAX application
  11. / / Is it a POST or a GET?
  12. ( $_POST [ 'yws_path' ] ) ? $_POST [ 'yws_path' ] : $_GET [ 'yws_path' ] ; $ path = ($ _POST [ 'yws_path'])? $ _POST [ 'yws_path']: $ _GET [ 'yws_path'];
  13. HOSTNAME . $path ; $ url = HOSTNAME. $ path;
  14. / / Open the Curl session
  15. curl_init ( $url ) ; $ session = curl_init ($ url);
  16. / / If it's a POST, put the POST data in the body
  17. $_POST [ 'yws_path' ] ) { if ($ _POST [ 'yws_path']) (
  18. '' ; $ postvars ='';
  19. $element = current ( $_POST ) ) { while ($ element = current ($ _POST)) (
  20. key ( $_POST ) . '=' . $element . '&' ; $ postvars .= key ($ _POST). '='. $ element. '&';
  21. $_POST ) ; next ($ _POST);
  22. )
  23. $session , CURLOPT_POST , true ) ; curl_setopt ($ session, CURLOPT_POST, true);
  24. $session , CURLOPT_POSTFIELDS , $postvars ) ; curl_setopt ($ session, CURLOPT_POSTFIELDS, $ postvars);
  25. )
  26. / / Do not return HTTP headers. Do return the contents of the call
  27. $session , CURLOPT_HEADER , false ) ; curl_setopt ($ session, CURLOPT_HEADER, false);
  28. $session , CURLOPT_RETURNTRANSFER , true ) ; curl_setopt ($ session, CURLOPT_RETURNTRANSFER, true);
  29. / / Make the call
  30. curl_exec ( $session ) ; $ xml = curl_exec ($ session);
  31. / / The web service returns XML. Set the Content-Type appropriately
  32. "Content-Type: text/xml" ) ; header ( "Content-Type: text / xml");
  33. ; echo $ xml;
  34. $session ) ; curl_close ($ session);
  35. ?>

This codcie you use curl a known PHP library used to bypass any restrictions on the most simple and known commands fopen() fread() etc ... It is sufficient to open the destination on our external domain with one of the many features available to our disposal by PHP, such as readfile() Unfortunately, often these functions are disabled or limited on some hosting, for security reasons. The curl however, are almost always available.

2. The good old IFRAME TAG

I still remember when in 1996 implementai one of the first techniques of Remote Scripting (as it was called at the time, when Ajax was just a detergent). The IFRAME tag is still used today, abused, adored and despised, depending on the programmer who uses it. The IFRAME tag is often referred to as "what not to do", a dangerous door for a hacker. Ultimately, then, with the introduction of the XMLHttpRequest object in browsers, the IFRAME is even more despised by the "purists Ajax." It's actually still used a lot, both for the inclusion of Widgets, Gadgets and Antipixel in blogs (if you have a blog is likely that your page is full of "holes" IFRAME or even know) or to bypass any block or lack of the same object XmlHttpRequest.
An IFRAME opens up a browser within the browser. This window can display an IFRAME external domain and is accessible from JavaScript code on the page parent. So here's another way to bypass the blocking of the XMLHttpRequest object.

3. Other techniques

There are also many other alternatives as appropriate and the circumstances in which we are (you can install specific tools or manipulate the Web Server to low level). You can use mod_rewrite or mod_proxy of apache or libraries as JSON to overcome the problem.
Other techniques (follow the links below on the "see also") are nice variations, but some have restrictions on browsers that support them, so be careful. The best, at least in my opinion, is the use of a simple proxy server in PHP.

4. Flash

Allow me to add flash between the techniques of overcoming the cross-domain, if only because I mentioned in a previous post: Ajax without HTTPRequest. Flash, of course, has nothing to do with the XHR object and, more than ever, nothing to do with Javascript. But we must keep in mind some important features:

  1. A Flash movie can interact with JavaScript and the DOM of the web page
  2. Javascript can interact with a Flash movie
  3. Adobe AIR is a system in which HTML, JavaScript / Ajax and Flash coexist in a harmonious and functional

Flash, unlike XHR object, has no such restrictions on cross-binding domain. In Flash there are a number of features aimed for the security and access control to different domains from where it is "turning" our movie. However they are easily set by code and depend largely on the choice of svilupparore who wrote the code. Access, then, to an RSS file of any domain is, in Flash, something very simple. Furthermore, instead of using a PHP page as a proxy, you can take advantage of Javascript's ability to communicate with Flash and then use it as a proxy.

An example of PHP proxy server for all

A simple example of how to write a PHP page that runs a proxy server minimal, which I used quite often ... ;)

PHP:
  1. $url ) { function getContent ($ url) (
  2. curl_init ( ) ; $ ch = curl_init ();
  3. 5 ; // set to zero for no timeout $ timeout = 5, / / set to zero for no timeout
  4. $ch , CURLOPT_URL , $url ) ; curl_setopt ($ ch, CURLOPT_URL, $ url);
  5. $ch , CURLOPT_RETURNTRANSFER , 1 ) ; curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);
  6. $ch , CURLOPT_CONNECTTIMEOUT , $timeout ) ; curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout);
  7. curl_exec ( $ch ) ; $ file_contents = curl_exec ($ ch);
  8. $ch ) ; curl_close ($ ch);
  9. / / Display file
  10. $file_contents ) ; return ($ file_contents);
  11. )

This simple function just uses the curl library to access a page that could be, for example, an XML RSS feed. In this way a call will receive the results via Ajax this simple proxy server PHP.

See also

Related Post

Was this article helpful?: Per nientePocoAbbastanzaMoltoMoltissimo
Loading ... Loading ...

4 comments to "Tunneling and proxy servers for Ajax and not just"

  1. getAvatar 1.0
  2. getAvatar 1.0
    December 10, 2007 upnews.it:

    undolog  »Blog Archive » Tunneling and proxy servers for Ajax and more ...

    Because of its ability to communicate with the server, the object € ™ XmlHttpRequest (XHR), used in Ajax technology (acronym for Asynchronous JavaScript and XML, which should be pronounced œegiacsâ â € €? Although we Italians prefer â € œaiacs ...

  3. getAvatar 1.0
    January 22, 2008 Napolux:

    Excellent article, I'll "deliciousizzo" on the fly : D

  4. getAvatar 1.0
    December 22, 2008 Very short trick: proxy with SimplePie RSS | Undolog.com:

    [...] Equip yourself for a proxy (tunneling) because of the protections imposed by both technologies (see Tunneling and proxy servers for Ajax and not only). If your site or blog is already SimplePie, you can write a simple proxy in [...]

Leave a comment

TAG XHTML PERMISSIONS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre>         // blocco generico [code][/code]       // blocco generico [as][/as]           // Actionscript [css][/css]         // CSS Style Sheet [html][/html]       // HTML [js][/js]           // Javascript [objc][/objc]       // Objective-C [php][/php]         // PHP [sql][/sql]         // SQL