François Romain
François Romain

Reputation: 14393

how to pass credentials with angular-http-auth?

Inside my app, authentication is working with angular-http-auth

when user fill the username / password form and submit, it targets the login() function from the controller :

$scope.login = function() {
    var credentials = Base64.encode($scope.username + ':' + $scope.password);
    $http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;

    User.login(                           // reference to the $resource service
        function() {                      // success callback
            authService.loginConfirmed(); // method of angular-http-auth
        }
    );

}

User is a service created with $resource

factory('User', function($resource){
    return $resource('url/to/json', 
        {}, 
        {   'login': { method: 'GET', isArray:true }
        });
})

and base64 is an encrypting service coming from here

This is working like this, but is there a way to pass the credentials through angular-http-auth instead of setting default headers through $http ?

Upvotes: 2

Views: 4581

Answers (1)

zumalifeguard
zumalifeguard

Reputation: 9016

The problem with doing this:

$http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;

is that you're now setting the "credentials" for all $http requests that are made. If you don't want to do that, and you want to pass the "credentials" with each $resource call directly, you can, which is what it looks like you're starting to do there.

return $resource('url/to/json', 
    {}, 
    {   'login': {
             method: 'GET',
             headers: { 'Authorization': 'Basic ' + credentials }
         }
    });

I didn't try this very example, but I have I similar code where the method is a POST so I call save() on the result of $resource before returning it, and the 'login' key is 'save'

But since you're doing a GET, with a custom "login" method, this should work.

Upvotes: 1

Related Questions