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

眉间皱痕 提交于 2019-12-11 03:57:19

问题


I am using node.js restify as backend to run a REST API server and angularjs as front-end to call the HTTP GET. The REST server uses HTTP Basic Authentication. The username is foo and password is bar.

I have tested that the backend code works by using a restify client. Here is the working client code;

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

I have trouble getting my angularjs http-get code to work. Here is the relevant code;

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

I cannot figure out what is wrong with the angularjs code. I am using restify authorizationParser. Are there any extra header requirements to get HTTP basic authentication working with restify authorizationParser?

The error message on the browser looks like this;

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

In the chrome debugger, this is what I see;

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

I am using this base64 angular module. https://github.com/ninjatronic/angular-base64

EDIT: I discovered there is nothing with the angular code. The problem lies with the restify server. The restify server supports static web server and when http basic authentication was enabled, this static web server stopped working.


回答1:


Inside the controller, you can pass the authentication header like this:

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


来源:https://stackoverflow.com/questions/34429313/what-is-wrong-with-this-http-get-basic-authentication-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!