jQuery 在 Ajax 调用中使用 http 基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27904082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:28:35  来源:igfitidea点击:

Using http basic authentication with Ajax call

jqueryajaxhttpauthenticationhttp-headers

提问by Ste

I need to contact a server to consume a HTTP service.

我需要联系服务器以使用 HTTP 服务。

Trying to reach the service with the browser, using https://example.com/serviceI get the basic authentication dialog.

尝试通过浏览器访问服务,使用https://example.com/service我获得基本身份验证对话框。

Changing the URL to https://username:[email protected]/serviceeasily bypasses that.

更改 URL 以https://username:[email protected]/service轻松绕过它。

Trying to do the same using Ajax always results in 401 Unauthorizedthough:

尝试使用 Ajax 做同样的事情总是会导致401 Unauthorized

$.ajax({
    url: 'https://username:[email protected]/service',
    // rest repeats
    type: "GET",
    async: true,
    success: function(text) { alert('success'); },
    error: function (text) { alert('error') },
    complete: function(text) { alert('complete'); }
});
$.ajax({
    url: 'https://example.com/service',
    username: username,
    password: password,
    // snip repeat
});
$.ajax({
    url: 'https://example.com/service',
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic "
            + btoa(username + ":" + password));
    },
    // snip repeat
});

回答by Lucas Leite

I struggled with a similar scenario myself.. What did the trick was using jsonp (ugh):

我自己也遇到了类似的情况。 使用 jsonp 有什么技巧(呃):

$.ajax({
        url: "https://localhost:8443/v1/accounts",
        type: 'GET',
        dataType: 'jsonp',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
        }
    })