14

在我对具有服务堆栈的服务器进行跨域调用之前,我已成功通过身份验证并获取我的令牌。

现在我想做另一个调用来检索数据:

$.ajax({
    beforeSend: function(xhr) {                  
        xhr.setRequestHeader('Authorization', 'Basic ' + getToken());   
    },
    type: "GET",
    url: requestUrl,
    xhrFields: {
        withCredentials: true
    },  
    async: true,
    dataType: 'json',
    crossDomain: true
})

当我查看我的谷歌浏览器开发工具控制台时,我看到了这个:

OPTIONS http://MyPc.company:82//customers 404 (Not Found) 
OPTIONS http://MyPc.company:82//customers Invalid HTTP status code 404 

XMLHttpRequest cannot load http://MyPc.company:82//customers. 
Invalid HTTP status code 404 (index):1

当我查看提琴手时,我看到了这个请求:

Inspectors => Auth:不存在授权标头。

检查员 => 原始:

OPTIONS http://MyPc.company:82//customers HTTP/1.1
Host: MyPc.company:82
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: GET
Origin: http://MyPc.company
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin, accept, access-control-allow-headers, authorization, access-control-allow-methods, content-type
Accept: */*
Referer: http://MyPc.company/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

为什么没有发送授权标头?乍一看,这似乎是我的起源问题。

4

1 回答 1

4

在 JavaScript 中

     jQuery.support.cors = true;

   function make_base_auth(user, password) {
      var tok = user + ':' + password;
      var hash = btoa(tok);
      return "Basic " + hash;
  }
   function DoTest() {
          var TestRequest = new Object();
          TestRequest.name = "Harry Potter";             
          TestRequest.Id = 33;
         var username = "admin";
         var password = "test"; 
      $.ajax({
          type: 'Post',
          contentType: 'application/json',
          cache: false,
          async: false,
          url: serverIP + '/TestAPI/'+ TestRequest.Id,
          data: JSON.stringify(TestRequest),
          dataType: "json",                  
          beforeSend: function (xhr) {                    
           xhr.setRequestHeader("Authorization", make_base_auth(username, password));
          },
       success: function (response, status, xhr) {
              var s= response.message;      
          },
          error: function (xhr, err) {
              alert(xhr.statusText);
          }
      });
  }

应该为 CORS 启用服务配置,例如

              Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization")); 

也许我之前的回答 可以帮助你。

或者更好的是来自社区资源的以下博客文章

带有自定义身份验证的 ServiceStack 上的 CORS BasicAuth

于 2013-10-24T17:34:19.113 回答