使用 header 身份验证的跨域请求

Cross domain request with header authentication

我需要发送一个 Get 跨域请求和 header 身份验证。

它在 Chrome 和 Firefox 中运行良好,但我在 Safari 和 IE 中遇到问题。同样在随机情况下 returns 401.

<script>
var url = 'username:password@anotherdomain.com';
$.ajax({
    url: url,
    dataType: 'jsonp',
    jsonpCallback: "callback",
    success: function(json) {
        alert(json);
    }
});
</script>

解决这个问题的最佳选择是什么?

对于 Internet Explorer 8 and 9,您需要使用 XDomainRequest Object

Internet Explorer 10+ 跨域请求与所有其他浏览器一样正常。

如文档中所述,您需要

  • 使用 var xdr = new XDomainRequest(); 创建 XDR 对象
  • 使用get方法打开连接使用xdr.open("get", "username:password@anotherdomain.com");
  • 使用xdr.send();
  • 将数据发送回服务器

完整的代码参考如上this thread by @Mark Pieszak

作为在 Internet Explorer 中设置 usernamepassword 的解决方法,您可以设置以下

DWORD for iexplore.exe to 0 in: [HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE].

如果我没有正确理解问题,您可以使用 beforeSend 回调为请求添加基本身份验证。不过,这与 jsonp 或跨源无关。

beforeSend: function (xhr) {
  xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
}

https://jsfiddle.net/rn9Lp304/

使用 getJSON

$.getJSON("url",function (data) {/*code here*/});

我会推荐你​​尝试两件事:

在ajax设置中,执行此操作:

$.ajaxSetup({
    ....,
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true,
    ....
});

在您的 ajax 请求中,除了 credentials 标志之外,像这样设置完整的 url。

'Access-Control-Allow-Origin: https://not-example.com'
'Access-Control-Allow-Credentials: true'

对于具有身份验证的服务器,这些浏览器不允许在此 header 中使用“*”。 Access-Control-Allow-Origin header 必须包含客户端传递的 Origin header 的值。