简体   繁体   中英

AngularJS $resource - Set custom header with username/password?

I want to create a new REST method for my login system, where I supply user credentials in a custom header. How can I do it in with AngularJS/ng-resource? I've tried the below code but the problem is when i try to get the username/password from the forms($scope.vm.username). This gives me 'undefined' if I do it it in the headers setup.

angular.module('BkSystemApp.controllers', ['ngResource'])

.controller('LoginController', function($scope, $location, $resource){
    //init
    $scope.vm = {};

    function getUserCredentials(){
        return ($scope.vm.username + ':' + $scope.vm.password)
    }

    //resources
    var Authentication = $resource('/users/authentication',{},{
        login:{
            method: 'GET',
            isArray: false,
            headers: {'Authentication':btoa(getUserCredentials())}
        }
    });

    //HTTP methods
    $scope.login = function(){
        Authentication.login(function(data){

        });     
    };
})

To have the $resource .login method compute the header string at method invocation time, the header configuation needs to have a header property with a value which is a function declaration, not a function invocation.

 //resources
var Authentication = $resource('/users/authentication',{},{
    login:{
        method: 'GET',
        isArray: false,
        //USE function declaration
        headers: {
           'Authentication': 
                function () {
                    return btoa(getUserCredentials())
                }
        }
        //NOT function invocation
        //headers: {'Authentication':btoa(getUserCredentials())}
    }
});

This way the Authentication value will be computed each time the login method gets invoked.

NOTE: It is not wise to send username and password in the header of an XHR GET request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM