Mastering Web Application

(Rick Simeone) #1

Securing Your Application


function($injector, queue) {
return function(promise) {
var $http = $injector.get('$http');
return promise.then(null, function(response) {
if(response.status === 401) {
promise = queue.pushRetryFn('unauthorized-server',
function() {return $http(response.config); }
);
}
return promise;
});
};
}])

Our interceptor watches for error responses that have a 401 status. It does this by
providing a handler for the second parameter of the call to then(). By providing
null for the first parameter, we indicate that we are not interested in intercepting
the promise object if it is resolved successfully.


When a request fails with a 401 error, the interceptor creates an entry in the
securityRetryQueue service, which is described later. This service will repeat
the failed request, when the queue is processed after a successful login.


The important thing to realize here is that promise handlers can either return a
value or a promise object:



  • If a handler returns a value, the value is passed straight on to the next
    handler in the chain

  • If a handler returns a promise object, the next handler in the chain is not
    triggered until this new promise object has been resolved (or rejected).


In our case, when the original response returns a 401 unauthorized error, we actually
return a new retry promise, for a retry item in the securityRetryQueue service
instead of the original promise object for the response. This new retry promise
object will be resolved, if the securityRetryQueue is retried and a new successful
response is received from the server, or rejected if the securityRetryQueue is
cancelled, or the response is another error.


While our original caller sits patiently waiting for some response to return from
the server, we can pop up a login box, allow the user to authenticate, and then
eventually retry the items in the queue. Once the original caller receives a successful
response, they are able to carry on, as though they had been authenticated all along.

Free download pdf