0

I am trying to accomplish two things here:

1) pass in a username and password from a login screen to getToken.getToken() which in turn calls getTokenFromServer.getToken which sets token to the returned token value.

2) call getToken.getToken each subsequent time from Angular controllers, but this time just returning the already retrieved token that I'm assuming is stored in the getToken factory since it's a singleton?

Am I on the right track here with AngularJS / Web API 2 authentication?

I know getTokenFromServer.getToken works if given a username and password it will return a valid token. But I am not sure what exactly to do from there in terms of saving a token for subsequent calls to controllers that need a token. Thank you for your help.

securityApp.factory("getToken", function (getTokenFromServer) {

    function getToken(userName, password) {

        var token;

        if (!!token) {
            getTokenFromServer.getToken(username, password).then(function (data) {
                token = data;
            });
        };

        return token;
    }

});


securityApp.factory("getTokenFromServer", function ($http, $q) {

    function getToken(userName, password) {

        return $http({
            method: 'POST', url: '/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            }
        })
        .then(function (result) {
            return result.data.access_token;

        }, function (errorResponse) {
            return $q.reject(errorResponse.data);
        });

    }

    return {
        getToken: getToken
    };

});
1
  • 2
    Keep the token in a cookie, and place it in the header of your subsequent server calls. Commented Oct 2, 2014 at 5:25

1 Answer 1

3

You need to obtain the access token from your Auth server only once (request token from the server) and until it expires.

Once you obtain the token you need to store it on html local storage and keep sending it with the authorization header for each subsequent request using httpInterceptor service.

I've written detailed series of posts and there is one exactly solves your issue. You can read about it more AngularJs Authentication using Web API 2

If you need further help drop me a comment.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. I'll have a look at your write up and give it a shot.
Your post was very helpful, thank you again for writing the article.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.