【问题标题】:What is wrong with this HTTP-Get Basic authentication code?这个 HTTP-Get Basic 身份验证代码有什么问题?
【发布时间】:2023-03-20 13:48:01
【问题描述】:

我使用 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);
});

我无法让我的 angularjs http-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 服务器上。 restify 服务器支持静态 web 服务器,当启用 http 基本认证时,这个静态 web 服务器停止工作。

【问题讨论】:

  • 错误是什么?
  • 我已编辑问题以显示错误。谢谢。

标签: javascript angularjs node.js restify basic-authentication


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-05-14
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多