Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
1  
Maybe this could help: stackoverflow.com/questions/18877715/… ? – ssougnez Dec 22 '15 at 10:46
up vote 6 down vote accepted

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) {
share|improve this answer
    
Your code looks ok but I have trouble getting it working. I have asked another question. stackoverflow.com/questions/34429313/… – user781486 Dec 23 '15 at 5:42
    
Your code is working. I think it is my server that is giving the problem. Marked as correct answer. – user781486 Dec 23 '15 at 7:25

Rather than using a library to encode your auth by base 64, you could just use:

window.btoa("user:pass")

it's supported by most browsers.

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.