jQuery的+ WCF.基本身份验证问题

Iev*_*ida 3 authentication ajax wcf jquery http-headers

我的服务是通过IIS中的基本身份验证设置保护的,我尝试使用Jquery从服务获取数据.

已启用跨域调用.

我有下一个请求标题

Host http:\\service.com
User-Agent Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Origin null
Access-Control-Request-Me... GET
Access-Control-Request-He... authorization
Pragma no-cache
Cache-Control no-cache
Run Code Online (Sandbox Code Playgroud)

回应

Content-Type text/html
Server Microsoft-IIS/7.5
WWW-Authenticate Basic realm="172.27.131.5"
X-Powered-By ASP.NET
Access-Control-Allow-Orig... *
Access-Control-Allow-Head... *
Date Fri, 12 Aug 2011 08:07:29 GMT
Content-Length 1293
Run Code Online (Sandbox Code Playgroud)

 $.ajax({
     headers : {
        "Authorization" : "Basic TVNF3TQtU1BGMjAx6C12bVxzbW4ydHBvaW50OlF3Z5J0eSEyM6Q1"
     },
     type: "GET",
     url: url,
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(data) {
      alert('ok!');
      formatData(format_type,data);
     },
     error: function(jqXHR, textStatus, errorThrown) {
          alert(textStatus + ' / ' + errorThrown);
     }
  });
Run Code Online (Sandbox Code Playgroud)

我也试着设定

 beforeSend : function(xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + Base64.encode(username + ':' + password));
        },
Run Code Online (Sandbox Code Playgroud)

但我有下一个错误:

请求标头字段Access-Control-Allow-Headers不允许授权

我做错了什么?

Luu*_*uuk 9

尝试将以下代码添加到WCF项目中的global.asax(仅在iis中托管时才有效):

protected void Application_BeginRequest(object sender, EventArgs e)
{
    EnableCrossDomainAjaxCall();
}

private void EnableCrossDomainAjaxCall()
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
        HttpContext.Current.Response.End();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jquery发出对WCF服务的OPTIONS调用,以检查是否允许调用.你必须匹配确切的标题.您也可以在此处下载示例:http://sameproblemmorecode.blogspot.com/2011/10/creating-secure-restfull-wcf-service.html.