Cross-domain AJAX

As mashups are getting more and more common a problem that keeps arising is how to include data from external domains in a safe way.

The reason why this is difficult is because the current implementations of the XMLHttpRequest API disallows access to other domains as a security measure (to avoid CSRF/XSRF).

Even though newer browsers are getting support for this using the crossdomain.xml policy file, this is still a feature that older browsers are unable to use.

So how can this be done with easyXDM? Well, it’s actually quite easy as easyXDM is actually shipped with a /cors/ (index.html) interface that exposes an easyXDM.Rpc instance that again exposes the following interface

request: function(config, fn){

To take us of this on the consumer you simply need the following code

var xhr = new easyXDM.Rpc({
    remote: "http://other.domain/cors/"
}, {
    remote: {
        request: {} // request is exposed by /cors/

With this up and running you can use

    url: "pathRelativeToRemote/getrest/",
    method: "POST",
    data: {foo:"bar"}
}, function(response) {

There you go, cross domain ajax!

The /cors/ implementation will adhere to the CORS standard and will verify the related headers before returning the response. If you want to skip this, then you can simply white-list all domains in the interface.

Note: This is for your security – you don’t want to go exposing all the resources on your domain to anyone now do you?

For more information: see the readme at github.

You can find the demo here.

This entry was posted in Examples/How-to's and tagged , , , , , , , , , . Bookmark the permalink.