AngularJS - 使用Basic Auth的http请求(连接到FreeNAS)

时间:2016-03-10 19:22:14

标签: python angularjs api httprequest

我试图在我的AngularJS应用程序中连接到FreeNAS的REST API(http://api.freenas.org/authentication.html)。 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.
  });

2 个答案:

答案 0 :(得分:0)

您需要创建一个用于在Base64中编码用户和密码的功能(“用户名:密码”)并添加授权标题。

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

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

一旦开始工作,请实施您发布的Base64工厂(How do I get basic auth working in angularjs?

希望有所帮助:)

答案 1 :(得分:0)

你可以这样试试。

$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.
  });