Sunday, 30 April 2017

Add authentication token in every http request call in angular js applications

In this post we are going to see how to pass the authentication token in every http request call in angular js application

authService:
*************
 mvcapp.service('authService', ['$localStorage', '$rootScope',function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }


}]);




Factory:
*********
mvcapp.factory('httpRequest', ['$q', 'authService', function ($q, authService) {

    var _interceptors = {
        request: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
                var loggedin = authService.getAuthCode();

                if (loggedin!=undefined && loggedin.Authcode != null)
                    config.headers["Authorization"] = "Bearer " + loggedin.Authcode;

            }
            return config;
        },
        response: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return response;
        },
        requestError: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
            }
            return $q.reject(config);
        },
        responseError: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return $q.reject(response);
        }
    };

    return _interceptors;

}]);



mvcapp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequest');
}]);



From this post you can learn how to pass the authentication token in every http request call.