Search code examples
asp.netangularjsrestwebmethod

Service Call on Page Generates Zone Security Error


This error is received on an ajax call

WebSocket Error: SECURITY_ERR, Cross zone connection not allowed

with a 500 error code also returned. I am able to get other responses which don't seem to be related to the error upon further testing. See below for where the reported error is.

From this Angular call

$http.post("Status.aspx/GetDataAsync", {})
     .then(function(response){ $scope.theData = data;},
           function(response){ $scope.result  = "Error!";}
     );

when attempting to call a page's code behind WebMethod which tellingly also makes a webservice call to a rest web service.

[System.Web.Services.WebMethod]
public static async Task<string> GetDataAsync()
{ 
   var httpresult = await (new HttpClient()).GetAsync("{Internal site rest service Url}");
   return await httpresult.Content.ReadAsStringAsync();
}

This reminds me of an old Silverlight cross-domain issue call...but I digress.

Question Can the zone issue be resolved or does one have to call rest services directly?


Attempt The use of CORS (see Enabling Cross-Origin Requests (CORS)) at the method level such as

 [System.Web.Services.WebMethod]
 [EnableCors("AllowAllOrigins", "AllowHeaders", "AllowAllMethods")]

to no luck.


Error

F12 Tools Error

This is where the error is found, in the F12 tools on Edge (and IE). Chrome does not report the issue.


Solution

  • You will need to set the Content Security Policy (CSP) of your page so that your {Internal site rest service Url} is not blocked by the browser.

    Here are links, combined, that helped me solve this issue: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src http://caniuse.com/#feat=contentsecuritypolicy

    For MVC, I placed the following in the web.config:

        <httpProtocol>
          <customHeaders>
            <add name="Content-Security-Policy" value="connect-src 'self' wss://localhost:7717" />
          </customHeaders>
        </httpProtocol>
    

    I was then able to create a websocket connection to wss://localhost:7717, but wasn't able to connect to any other port.

    Browsers block these kinds of requests to prevent cross-zone script attacks, so you need your page to set the policy, done through the http header. I'm working on a similar issue. I'm missing something, but I think this is the right direction. I need others input because this isn't quite solving the issue. It's closer, though.