Add HTTP basic authentication to this HTTP GET in angularjs

前端 未结 2 1566
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 20:47

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

    .controller(\'imptViewCtrl\', [\'$         


        
2条回答
  •  自闭症患者
    2020-12-16 21:30

    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) {
    

提交回复
热议问题