Austin Harris
Austin Harris

Reputation: 5410

AngularJS / Web API 2 token Authenticaion

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
    };

});

Upvotes: 0

Views: 176

Answers (1)

Taiseer Joudeh
Taiseer Joudeh

Reputation: 9043

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.

Upvotes: 3

Related Questions