AJAX POST请求隐藏基本认证凭证



我一直在研究将AJAX POST请求发送到我的API的方法,并且我正在尝试了解如何正确地传递基本身份验证凭据。

          Interface                    API

https://www.example.com/app/ -------> https://api.example.com/

使用这个例子,我在StackOverflow上发现——没有人可以查看JS的源代码,看到我的用户名和密码在明文中,并有权访问我所有的API函数吗?

如果是,我如何传递我的用户名和密码而不显示给世界?

$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});

是的,如果你在JavaScript中硬编码你的用户名和密码,全世界都能看到并使用它们。

你不应该使用基本认证来保护web api。正如我在这个答案中描述的那样,有几种选择。我的偏好是OAuth2。在JavaScript客户端中使用它,您希望查看隐式流,这是专门针对不受信任的客户端的。

最新更新