Thursday, June 28, 2012

Cross Site Scripting PHP Proxy

I needed to access a REST web service from jQuery, but Chrome would throw an error during the ajax call due to the "origin" policy.  It's possible to setup a CORS filter with Tomcat and Apache, but that sounded like a lot of work.

Instead, if you can use PHP, just download the following PHP proxy:
https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/proxy.php

Two changes are needed:

  1. Edit line 176 such that it reads  $url_query_param = 'url';
  2. Either fix the regexp at lines 172 and 173 which checks that the call is to sales force.com (set it to match your website) or  comment out lines 206 to 212 (potentially dangerous).
Now your $.ajax call needs to be modified so that the target url is part of the url.  Everything else is seamless.  See below.

 
 var req = $.ajax({
    type: 'GET',
    contentType: 'application/json',
    mimeType: 'application/json',
    url: 'http://proxy-server/app/proxy.php?mode=native&url=http://api-server/api/object/'+$("#objectID").val(),
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
 alert("Got data successfully");
 $('#responseData').text(JSON.stringify(data));
 },
    error: function(xhr, textStatus, error) {
 alert("Error: " + textStatus);
 } 
  });
That's it!

1 comment:

tahir sumar said...
This comment has been removed by a blog administrator.

Labels

Blog Archive

Contributors