【问题标题】:AJAX POST Request Hide Basic Auth CredentialsAJAX POST 请求隐藏基本身份验证凭据
【发布时间】:2015-10-23 05:05:14
【问题描述】:

我一直在研究将 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));             
    }
});

【问题讨论】:

    标签: ajax authentication basic-authentication


    【解决方案1】:

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

    您不应使用基本身份验证来保护 Web API。正如我在this answer 中描述的那样,有几种选择。我的首选是OAuth2。从 JavaScript 客户端使用它,您想查看隐式流,它专门用于不受信任的客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多