Search code examples
angularjsangular-http-interceptors

how to develop angularjs interceptor to control session


i'm a student, and recently working on angularJS interceptor and trying to develop one to control session management. I am new in mean stack development and need help. Does anybody have a working example of session management by angularJS?

Really appreciate your help and time.


Solution

  • If you want a token based control you can do something like this:

    Your interceptor:

    angular.module('yourApp').factory('YourHttpInterceptor', ['$q', '$window',
    function($q, $window) {
        return {        
            'request': function(config) {
                config.headers = config.headers || {};
    
                // If you have a token in local storage for example: 
                if ($window.localStorage.token) {
                    // Add the token to "Authorization" header in every request
                    config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
                    // In your server you can check if the token is valid and if it's not,
                    // in responseError method you can take some action
                }
    
    
                // Handle something else
    
                return config;
            },       
    
            // Optional method
            'requestError': function(rejection) {
                // do something on request error 
    
                if (canRecover(rejection)) {
                    return responseOrNewPromise
                }
                return $q.reject(rejection);
            },        
    
            // Optional method        
            'response': function(response) {
                // do something on response success
                return response;
            },
    
            // optional method 
            'responseError': function(rejection) {
                // Here you can do something in response error, like handle errors, present error messages etc.
    
                if(rejection.status === 401) { // Unauthorized 
                    // do something
                }
    
                if (canRecover(rejection)) {
                    return responseOrNewPromise
                }
                return $q.reject(rejection);
            }
        };
    }]);
    

    And in your module config register the interceptor:

    angular.module('yourApp', []).config(function($httpProvider) {
        $httpProvider.interceptors.push('YourHttpInterceptor');
    }
    

    As you can see in this post a token based authentication follow this steps(almost always) :

    1. The client sends its credentials (username and password) to the server.
    2. The server authenticates them and generates a token with an expiration date.
    3. The server stores the previously generated token in some storage with user identifier, such as a database or a map in memory.
    4. The server sends the generated token to the client.
    5. In every request, the client sends the token to the server.
    6. The server, in each request, extracts the token from the incoming request, looks up the user identifier with the token to obtain the user information to do the authentication/authorization.
    7. If the token is expired, the server generates another token and send it back to the client.