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.
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.
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.
AngularJS interceptors offer a convenient way to modify request made by the $http service both before they are sent and after they return.
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.
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) :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With