需要通过JavaScript(在www.domain1.com中)使用Basic Auth进行REST GET调用。REST API在domain2.com中。REST API返回带有CORS特定的HTTP标头。我需要支持IE,Chrome和Firefox。JavaScript下面进一步解释了该问题–
没有基本身份验证(IE 10,Chrome和Firefox中的WORKS,通过XDomainRequest对象处理较旧的IE)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
使用基本身份验证(仅IE 10中的WORKS,Chrome和Firefox中失败)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true, username, password);
使用基本身份验证(Chrome和Firefox中失败)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
xhr. withCredentials = “true”;
使用基本身份验证(Chrome和Firefox中失败)
$.ajax({
type: 'GET',
url: jsonp_url,
dataType: "json",
username: username,
password: pwd,
beforeSend: function (xhr) {xhr.withCredentials = true; },
success: function (result) { },
error: function (xhr, ajaxOptions, thrownError) {
}
我很想在这里获得一个可以在具有Basic Auth的Chrome和FireFox中使用的解决方案
解决了 注意,浏览器分两步通过Authentication进行跨域调用-在实际请求之前进行预检调用。在IE和[Chrome + Firefox]中,此预检呼叫的性质有所不同。IE发出HTTP GET预检调用,然后返回401,然后在实际请求中发送身份验证详细信息。但是,Chrome和Firefox通过执行HTTP OPTIONS调用来检查Web服务器作为CORS支持的所有功能(允许哪个域/是否支持GET / POST等),从而采取了更为安全的方法,而下一个调用与实际的HTTP GET请求一起进行与身份验证。
不幸的是,API方面的编码方式是对每个Http调用进行身份验证。这就是为什么HTTP OPTIONS调用也返回401的原因。[chrome + Firefox]在预检调用后立即引发异常。
在API方面,修改了在OPTIONS调用下不返回401的代码,并且该代码开始工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句