需要通过 JavaScript(在 www.domain1.com 中)使用基本身份验证进行 REST GET 调用。 REST API 位于domain2.com 中。 REST API 返回 CORS 特定的 HTTP header 。我需要支持 IE、Chrome 和 Firefox。下面的 JavaScript 进一步解释了这个问题 –
无需基本身份验证(适用于 IE 10、Chrome 和 Firefox,通过 XDomainRequest 对象处理旧版 IE)
var xhr = new XMLHttpRequest(); xhr.open(method, url, true);
使用基本身份验证(仅在 IE 10 中有效,在 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) { }
我很想在这里获得一个可在 Chrome 和 FireFox 中使用且具有基本身份验证功能的解决方案
最佳答案
已经解决了。请注意,浏览器通过身份验证分两步进行跨域调用 - 在实际请求之前进行预检调用。这种预检调用的性质在 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,并且它开始工作。
关于jquery - 在 Firefox 和 Chrome 中,使用基本身份验证的基于 XMLHttpRequest 的 CORS 调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19234892/