Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to develop angularjs interceptor to control session

Tags:

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.

like image 681
jatinder bhola Avatar asked Jun 01 '16 16:06

jatinder bhola


People also ask

How do you implement an interceptor in AngularJS?

Angular applies interceptors in the order that you provide them. If you provide interceptors A, then B, then C, requests will flow in A->B->C, and responses will flow out C->B->A. In the example app, we have all the interceptors provided, but we only use one at a time. This is done by checking the path.

How do you create an angular interceptor?

The first step is to build the interceptor. To do this, create an injectable class that implements HttpInterceptor. Any interceptor we want to create needs to implement the HttpInterceptor interface. This means that our new class should have a method called intercept with parameters HttpRequest and HttpHandler.

What is AngularJS interceptor?

AngularJS interceptors offer a convenient way to modify request made by the $http service both before they are sent and after they return.

Can we create multiple interceptors in angular?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project. Now we create interceptor.


1 Answers

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.
like image 70
Gabriel Hobold Avatar answered Sep 28 '22 02:09

Gabriel Hobold