PortiBlog

Calling external REST service from a SharePoint hosted App using the Web proxy

15 januari 2015

In this blog post we will explain one of the ways to call an external REST service from the JS code of a SharePoint App. In order to prevent cross-site scripting attacks the browsers would not allow your code to make calls to external services, it will allow you to call only the domain from which the application is loaded.

One way to work around this is to use the Web Proxy, provided by SharePoint 2013. The approach is simple - your JS code will call a specific REST endpoint (/_api/SP.WebProxy.invoke) with all the parameters needed for the actual call. 

The SharePoint will then call the actual service and pass the response back. This way the client browser communicates only with the SharePoint app web.

So how do we implement this?First we should make sure that the SP.js file is referenced and create a new SP.WebRequestInfo object. We should set all the properties needed for the request, like URL, method, etc. As the call is asynchronous we should also provide a success and error functions. Finally we call the load method in the $(document).ready event.


“use strict”; 
 
var Portiva = window.Portiva || {};  
Portiva.Response; 
 
Portiva.DataReader = function () { 
 
    var load = function () { 
 
            var ctx = SP.ClientContext.get_current(); 
            var request = new SP.WebRequestInfo(); 
 
            // build the url according to the current scenario or user input
           var requestUrl = “http://www.portiva.nl/service?query=something:abc” 

            request.set_url(); 
            request.set_method(“GET”); 
            window.Portiva.Response = SP.WebProxy.invoke(ctx, request); 
 
            ctx.executeQueryAsync(onSuccess, onError); 
 
        }, 
 
        onSuccess = function () { 
            var xmlDoc = $.parseXML(window.Portiva.Response.get_body()); 
             // parse and use the response
        } 
 
        onError = function (err) { 
            alert(JSON.stringify(error)); 
        }; 
 
    return { 
            load: load, 
    }; 
 
}(); 

$(document).ready(function () { 
    Portiva.DataReader.load(); 
}); 

Before firing this off we should add the remote domain as trusted. This is another security feature that prevents the SharePoint from making calls to unwanted domains, in case that there is a malicious JavaScript code executed in the app. To add our domain to the allowed list the following RemoteEndpoint entry should be added to the app manifest:


<RemoteEndpoints> 
    <RemoteEndpoint Url=”http://www.someprovider.com”/> 
</RemoteEndpoints> 

One consideration that is notable to mention is that the SharePoint front-end server should have access to the remote endpoint. In some situations there might be a firewall that prevents the requests from being executed.

Submit a comment

Dit vind je vast ook interessant.