此HTTP Get-Basic身份验证代码有什么问题

What is wrong with this HTTP-Get Basic authentication code?

本文关键字:什么 问题 代码 身份验证 HTTP Get-Basic      更新时间:2023-09-26

我使用node.js restify作为后端来运行REST API服务器,并使用angularjs作为前端来调用HTTP GET。REST服务器使用HTTP基本身份验证。用户名为foo,密码为bar

我已经通过使用restify客户端测试了后端代码的工作原理。这是正在工作的客户端代码;

var client = restify.createJsonClient({
    url: 'http://127.0.0.1'
});
client.basicAuth('foo', 'bar');
client.get('/alert?list=alertList', function(err, req, res, obj) {
    console.log(obj);
});

我很难让angularjshttp-get代码正常工作。这是相关代码;

.controller('ViewCtrl', ['$scope', '$http', '$base64', 
        function ($scope, $http, $cookies, $base64) { 
          var url = '127.0.0.1/alert?list=alertList';
          var auth = $base64.encode('foo:bar');
          $http.defaults.headers.common['Authorization'] = 'Basic ' + auth;
          $http.get(url).then(function (response) {
                tableData = response.data;
                //handle data
          });
}

我不知道angularjs代码出了什么问题。我正在使用restify authorizationParser。使用restify authorizationParser进行HTTP基本身份验证是否有任何额外的头要求?

浏览器上的错误消息如下所示;

{
code: "NotAuthorized",
message: ""
}

在chrome调试器中,这就是我所看到的;

Request Method:GET
Status Code:403 Forbidden
Remote Address:127.0.0.1:80
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2,ja;q=0.2
Cache-Control:max-age=0
Connection:keep-alive
Host:127.0.0.1
If-Modified-Since:Wed, 23 Dec 2015 02:22:04 GMT
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

我正在使用这个base64角度模块。https://github.com/ninjatronic/angular-base64

编辑:我发现角度代码什么都没有。问题出在不稳定的服务器上。restify服务器支持静态web服务器,当启用http基本身份验证时,此静态web服务器停止工作。

在控制器内部,您可以像这样传递身份验证头:

var url = '127.0.0.1/alert?list=alertList';
var auth = $base64.encode('foo:bar');
var headers = {"Authorization": "Basic " + auth};
$http.get(url, {headers: headers}).then(function (response) 
     tableData = response.data;
     //handle data
});