Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an existing angularjs code which makes a HTTP GET. Extracted below is some relevant code inside the controller.

    .controller('imptViewCtrl', ['$scope', '$http', 
        function ($scope, $http, ) {
                    var url = $configuration.webroot + '/impt/list?list=testlist';
                    $http.get(url).then(function (response) {
                               tableData = response.data;
                               });
        }]);

I would like to add HTTP basic authentication to the HTTP GET. The username is foo and the password is bar. How can this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because in basic authentication, the username and password are decode by base64. You need to find a library to do this work for comfortable first.

https://github.com/ninjatronic/angular-base64

After that, load base64 into your app and config headers.

angular
    .module('myApp', ['base64'])
    .config(function($httpProvider, $base64) {
        var auth = $base64.encode("foo:bar");
        $httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
    })

You can also provide the authentication header to get function seprately if you like.

var auth = $base64.encode("foo:bar"), 
    headers = {"Authorization": "Basic " + auth};
$http.get(url, {headers: headers}).then(function (response) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...