Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - store basic authentication on login

I'm banging my head on a wall with this - I'm relatively new to working with APIs and have yet to do anything that requires authentication.

I'm stuck with sending a POST request to the API. The endpoint for creating a piece of content is:

/entity/node

I can send a successful POST request if I send the following:

headers: {
       "Authorization": "Basic YWRtaW46MTIzcXdl", //admin:123qwe
   },

The problem I am having is with Authorization. I'm specifying Basic and then an encoded string here, which is my admin login. So when hardcoded, I can post.

My question - when the user logs in correctly, I need the headers to be set so that all future post requests work. How can I do this in AngularJS?

I have tried passing a dynamically generated code:

"Authorization": "Basic " + auth,

where auth is a base64 encoded user:pass, but this does not work. My thinking is that this value needs to be stored somewhere for retrieval whenever a POST request is made. But how?

like image 442
Matt Saunders Avatar asked Jul 30 '15 12:07

Matt Saunders


Video Answer


1 Answers

Call this once you have a token:

$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
    if (authToken !== null) {
        var headers = headersGetter();
        angular.extend(headers, 'Authorization: basic ' + authToken);
    }

    return data;
});

EDIT: Have not tested it, but it should be something like:

myApp.provider('authService', function() {

    var authToken = null;

    this.$get = ['$httpProvider', function($httpProvider) {
        return {
            configure: configure,
            setAuthToken: setAuthToken
        }
    };

    function configure() {
        $httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
            if (authToken !== null) {
                var headers = headersGetter();
                angular.extend(headers, 'Authorization: basic ' + authToken);
            }

            return data;
        });
    }

    function setAuthToken(token) {
        authToken = token;
    }
});

and then inject authService to your app config and call authService.configure()

like image 198
Tzach Ovadia Avatar answered Sep 22 '22 01:09

Tzach Ovadia