jquery - 通过 Ajax 调用使用 http 基本身份验证

标签 jquery ajax http authentication http-headers

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

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

将 URL 更改为 https://username:password@example.com/service 很容易绕过它。

尽管尝试使用 Ajax 执行相同的操作总是会导致 401 Unauthorized:

$.ajax({
    url: 'https://username:password@example.com/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
});

最佳答案

我自己也遇到过类似的情况.. 诀窍是使用 jsonp(呃):

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

关于jquery - 通过 Ajax 调用使用 http 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27904082/

相关文章:

http - 在 Indy 中创建视频流服务器

javascript - slider 中的 Angular JS 过滤器

jquery - 在主 div 中滚动 div 的集合

ajax - 安全的 ajax 表单 POST

c++ - 使用 AJAX 从 HTML 页面到在同一服务器上运行的 C++ 应用程序的两种方式通信

php - 如何在完成 PHP 脚本执行之前接收 jQuery post 响应?

http - AWS Lambda 发布

http - 如果 HTTP 状态是错误代码,Chrome 无法下载响应正文

javascript - JQuery Block UI 元素阻塞问题

javascript - Offline.js - 在线时检查?