【问题标题】:AngularJS - http request with Basic Auth (connect to FreeNAS)AngularJS - 带有基本身份验证的 http 请求(连接到 FreeNAS)
【发布时间】:2016-03-10 19:22:13
【问题描述】:

我正在尝试在我的 AngularJS 应用程序中连接到 FreeNAS (http://api.freenas.org/authentication.html) 的 REST API。 API 使用用户名和密码的基本身份验证。

在python中这是一件非常简单的事情,因为只有一行代码:

requests.get('http://freenas.mydomain/api/v1.0/account/bsdusers/',auth=('root', 'freenas'))

我试图为 AngularJS 找到一些东西,但只是因为令人痛苦的代码而跌跌撞撞,例如How do I get basic auth working in angularjs?

有没有类似的东西:

$http({
  method: 'GET',
  url: 'http://freenas.mydomain/api/v1.0/account/bsdusers/',
  auth: ['username':'root', 'password':'pw']
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

【问题讨论】:

    标签: python angularjs api httprequest


    【解决方案1】:

    您需要创建一个函数,用于在 Base64("username:password") 中对用户和密码进行编码,并添加 Authorization 标头。

    您可以尝试在这里https://www.base64encode.org/ 对您的用户名和密码进行编码,看看它是否有效。 "root:freenas" 是 cm9vdDpmcmVlbmFz 你可以试试下面的代码。

    $http.defaults.headers.common['Authorization'] = 'Basic cm9vdDpmcmVlbmFz';
    

    一旦你开始工作,就可以实现你发布的 Base64 工厂 (How do I get basic auth working in angularjs?)

    希望对你有帮助:)

    【讨论】:

      【解决方案2】:

      你可以这样试试。

      $http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"}; 
      $http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('root' + ':' + 'freenas');
      $http({
        method: 'GET',
        url: 'http://freenas.mydomain/api/v1.0/account/bsdusers/'
      }).then(function successCallback(response) {
          // this callback will be called asynchronously
          // when the response is available
        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
        });
      

      【讨论】:

        猜你喜欢
        • 2019-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 2016-09-29
        • 2017-07-23
        • 1970-01-01
        相关资源
        最近更新 更多