asp.net - 经过身份验证的服务不支持跨域 javascript 回调。通过 SSL 代理对 WCF 服务进行 AJAX 查询

标签 asp.net ajax wcf jsonp

我有一个 WCF/SVC Web 服务,由通过 AJAX 的 JavaScript 调用使用。 该页面通过位于 DMZ 中的 SSL 代理 (https://gate.company.com/MyPage) 进行访问,然后将请求转发到内部 Web 服务器 (http://myLocalWebServer/MyPage)。

经过大量的谷歌搜索和尝试,我能够通过参数 crossDomainScriptAccessEnabledAccess-Control-Allow-Origin 使其工作。尽管如此,它仅在身份验证模式设置为 false 或用户尚未登录时才起作用。一旦从需要登录(表单例份验证)的页面内进行调用,它就不再起作用。我收到的错误消息是:

cross domain javascript callback is not supported in authenticated services

但是,一旦我注销并从不 protected 页面进行调用,它就会再次起作用。

我的服务是这样的

namespace MyNameSpace
{
   [ServiceContract(Namespace = "MyNameSpace")]
   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   public class Service
   {
      [OperationContract]
       public string[] GetDropDownData(string id)
      {
         List<string> resultList = new List<string>();
         ...
         return resultList.ToArray();
      }
   }
}

JavaScript中的服务调用和回调方法:

function fillDropdwon(dropId){
    jQuery.ajax({
        type: "POST",
        dataType: "jsonp",
        contentType: "application/json; charset=utf-8",
        cache: true,
        url: "Service.svc/GetDropDownData",
        data: '{"dropId":"' + dropId + '"}',
        jsonpCallback: "onDone",
        error: function (a,b,c) {
            alert("error");
        }
    });
}

// Callback-Methode after ServiceCall
function onDone(result) {
   var theDropDown = jQuery("#<%= cboSelection.ClientID %>");
    if (theDropDown.length > 0) {
        //Clear the old entries
        theDropDown.empty();

        //Add an empty entry
        if ("<%= cboSelection.ShowEmptyRow %>".toLowerCase() == "true") {
            theDropDown.append($('<option></option>'));
        }

        // Add the found items
        for (var i = 0; i < result.length; i++) {
            var text = result[i];
            theDropDown.append($('<option></option>').val(text).html(text));
        }
    }
}

涉及服务的 web.config 部分:

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="MyNameSpace.ServiceAspNetAjaxBehavior">
        <enableWebScript />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  <standardEndpoints>
    <webScriptEndpoint>
      <standardEndpoint crossDomainScriptAccessEnabled="true" name=""/>
    </webScriptEndpoint>
  </standardEndpoints>
  <services>
    <service name="MyNameSpace.Service">
      <!-- Service endpoint for HTTPS -->
      <endpoint address="" behaviorConfiguration="MyNameSpace.ServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="jsonpBinding" contract="MyNameSpace.Service" /> -->
    </service>
  </services>
  <bindings>
    <webHttpBinding>
      <binding name="jsonpBinding" crossDomainScriptAccessEnabled="true">
        <security mode="None" />
      </binding>
      <binding name="jsonpSslBinding" crossDomainScriptAccessEnabled="true">
        <security mode="Transport" />
      </binding>
    </webHttpBinding>
  </bindings>
</system.serviceModel>

我首先尝试使用 ASP.NET AJAX 代理来调用服务,但这不起作用,因为调用是直接对网络服务器进行的,这不是 SSL,而且我得到的错误或多或少是:'Page https://gate.company.com/MyPage 尝试从页面 http://myLocalWebServer/MyPage 加载而不保存内容...'。这就是我使用上面列出的 AJAX 调用的原因。

function fillDropdwon(dropId){
   var service = new MyNameSpace.Service();
   service.GetDropDownData(dropId, onDone);
}

我还尝试在 web.config 中添加以下内容

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <!-- Enable Cross Domain AJAX calls -->
      <remove name="Access-Control-Allow-Origin" />
      <add name="Access-Control-Allow-Origin" value="https://gate.company.com"/>
    </customHeaders>
  </httpProtocol>
</system.webServer>

我检查了发送到服务器的 header ,发现当我未登录时, header 如下所示:

Request URL:`https://gate.company.com/MyPage/Servic.svc/GetDropDownData?callback=onDone`
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,fr-CH;q=0.2,fr;q=0.2
Connection:keep-alive
Content-Length:161
Content-Type:application/json; charset=UTF-8
Cookie:__utma=174172730.1157990369.1360852643.1381229705.1383150435.9; __utmc=174172730; __utmz=174172730.1369635484.4.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); promopost=oaezz3fzzj0o4l3fccxh0ss1;
ASP.NET_SessionID=
Host:`gate.company.com`
Origin:`https://gate.company.com`
Referer:`https://gate.company.com/MyPage/QuickCalculator.aspx?ObjectIdentity=47a93f52-6be6-4bd6-9600-e8eb9c8ff360`
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
callback:onDone
Request Payloadview source
{dropId:123}
dropId: "123"
Response Headersview source
Cache-Control:private
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:1339
Content-Type:application/x-javascript
Date:Sun, 01 Dec 2013 15:14:25 GMT
Keep-Alive:timeout=15, max=97
Server:Microsoft-IIS/7.5
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-Powered-By

响应如下所示。

onDone(["result1","result2"]);

当我从 protected 页面内调用该服务时,我得到以下信息:

Request URL:`https://gate.company.com/MyPage/Servic.svc/GetDropDownData?callback=onDone`
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,fr-CH;q=0.2,fr;q=0.2
Connection:keep-alive
Content-Length:161
Content-Type:application/json; charset=UTF-8
Cookie:__utma=174172730.1157990369.1360852643.1381229705.1383150435.9; __utmc=174172730; __utmz=174172730.1369635484.4.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); promopost=oaezz3fzzj0o4l3fccxh0ss1;
**ASP.NET_SessionID=; .ASPXAUTH=AB5ADCE12C7847CA452DD54D903E6787C7D1F0009B9E3277D2EC50DE9C421D1331B87A6DCA2432993933794AB9BDE833E44EC58E217D5AA1D588132C6E1C67D4AD7692840359D9A719EC2A53826CF54FDC0943B4E0AB29093920143E1E987080AC7C35E63594FD678535972D06AEC0AAF74AF8BE8DFC3746B499CB032E7771F10B924110DB344824B3253F9BECB3CDD8**
Host:`gate.company.com`
Origin:`https://gate.company.com`
Referer:`https://gate.company.com/MyPage/QuickCalculator.aspx?ObjectIdentity=47a93f52-6be6-4bd6-9600-e8eb9c8ff360`
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
callback:onDone
Request Payloadview source
{dropId:123}
dropId: "123"
Response Headersview source
Cache-Control:private
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:1339
Content-Type:application/x-javascript
Date:Sun, 01 Dec 2013 15:14:25 GMT
**jsonerror:true**
Keep-Alive:timeout=15, max=97
Server:Microsoft-IIS/7.5
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
**X-Powered-By:ASP.NET**

响应如下所示。

onDone({"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"Cross domain javascript callback is not supported in authenticated services.","StackTrace":"   bei System.ServiceModel.Dispatcher.JavascriptCallbackMessageInspector.AfterReceiveRequest(Message& request, IClientChannel channel, InstanceContext instanceContext)\u000d\u000a   bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.AfterReceiveRequestCore(MessageRpc& rpc)\u000d\u000a   bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a   bei System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)","Type":"System.NotSupportedException"},"ExceptionType":"System.NotSupportedException","Message":"Cross domain javascript callback is not supported in authenticated services.","StackTrace":"   bei System.ServiceModel.Dispatcher.JavascriptCallbackMessageInspector.AfterReceiveRequest(Message& request, IClientChannel channel, InstanceContext instanceContext)\u000d\u000a   bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.AfterReceiveRequestCore(MessageRpc& rpc)\u000d\u000a   bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a   bei System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"},500);

主要区别在于“已登录”版本有一个 SessionIDjsonerror:true

有办法解决这个问题吗?

是否无法通过在调用之前更改 header 或类似操作来“禁用”AJAX 请求的身份验证。或者我的代码 web.config 有什么错误吗?

我很感激任何提示,因为我已经尝试了很长时间。

最佳答案

我终于找到了解决问题的方法。我写下了解决问题的步骤,希望对遇到类似问题的人有所帮助。

我首先使用 ASP.NET AJAX 代理并进行如下调用。

var service = new SDAG.Post.PPT.Website.Service();
service.GetDropDownData(dropId, onDone);

但是,这在我的环境配置中不起作用,SSL 代理通过端口 80(上面列出)在内部转发到 Web 服务器。我收到错误消息:

The page at <code>'https://gate.company.com/MyPage/Page.aspx?ObjectIdentity=f5c0c016-4828-4935-a7a9-73f3ba47a1ed'</code> was loaded over HTTPS, but displayed insecure content from <code>'http://myLocalWebServer.company.com/MyPage/Service.svc/GetDropDownData'</code>: this content should also be loaded over HTTPS.

ScriptResource.axd?d=8mniuUQAKIvBIxCF_O9BRQpND31cf-SHqs1HBOCcP0DdxGNo4-nOZcF0WZIDoCtTdw5mZIOSt0veif…:2

OPTIONS <code>http://myLocalWebServer.company.com/MyPage/Service.svc/GetDropDownData</code> 405 (Method Not Allowed) ScriptResource.axd?d=8mniuUQAKIvBIxCF_O9BRQpND31cf-SHqs1HBOCcP0DdxGNo4-nOZcF0WZIDoCtTdw5mZIOSt0veif…:2

OPTIONS <code>http://myLocalWebServer.company.com/MyPage/Service.svc/GetDropDownData</code> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>'https://gate.company.com'</code> is therefore not allowed access. ScriptResource.axd?d=8mniuUQAKIvBIxCF_O9BRQpND31cf-SHqs1HBOCcP0DdxGNo4-nOZcF0WZIDoCtTdw5mZIOSt0veif…:2

XMLHttpRequest cannot load <code>http://myLocalWebServer.company.com/MyPage/Service.svc/GetDropDownData</code>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>'https://gate.company.com'</code> is therefore not allowed access. Page.aspx?ObjectIdentity=f5c0c016-4828-4935-a7a9-73f3ba47a1ed:1

Refused to get unsafe header "jsonerror" 

我发现通过在 web.config 中的 webservice 绑定(bind)配置中使用 crossDomainScriptAccessEnabled 并通过 jQuery 使用 Jsonp Ajax 调用,它确实有效(请参阅上面的代码) 但是:它仅在页面的非授权区域有效。一旦用户在登录页面上进行身份验证,调用就不再有效。它告诉我经过身份验证的服务不支持跨域 javascript 回调

终于,我找到了解决办法。 该错误消息来自 web.config 中配置的 crossDomainScriptAccessEnabled。当我删除它时, jsonp 调用不再起作用。所以我所做的就是删除 crossDomainScriptAccessEnabled 并用常规 json 调用替换 jsonp 调用。

jQuery.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        cache: true,
        url: "Service.svc/GetDropDownData",
        data: '{"dropId":"' + dropId + '"}',
        error: function (xhr, textStatus, errorThrown) {
            // Ignore in my case...
        },
        success: function (data, textStatus, xhr) {
            fillSubList(data.d);
        }
    });

function fillSubList(result) {
    var theDropDown = jQuery("#<%= cboSelektion.ClientID %>");
    if (theDropDown.length > 0) {
        //Clear the old entries
        theDropDown.empty();

        //Add the empty one
        if ("<%= cboSelektion.ShowEmptyRow %>".toLowerCase() == "true") {
            theDropDown.append($('<option></option>'));
        }

        // Add the found items
        for (var i = 0; i < result.length; i++) {
            var text = result[i];
            theDropDown.append($('<option></option>').val(text).html(text));
        }
    }
}

关于asp.net - 经过身份验证的服务不支持跨域 javascript 回调。通过 SSL 代理对 WCF 服务进行 AJAX 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978380/

相关文章:

c# - WCF 以 JSON 格式返回 double 并在昏迷后限制数字

c# - ASP.NET 成员资格/自动登录现有用户

php - 什么时候用node.js,什么时候用ajax?

c# - 使用 Amazon Web Services (EC2) 和 c# Windows Service/WCF 进行远程调试

JavaScript : Ordering AJAX calls

javascript - AJAX 成功收到 JSON 响应但未解析

c# - WCF 不反序列化值类型。神秘行为

asp.net - 当更新面板位于主页中时保持滚动位置

c# - IIS/asp.net 中的静态方法和调用堆栈

c# - 使用 ASP.NET 中的函数设置 imageURL