Mastering Web Application

(Rick Simeone) #1

Securing Your Application


Instead, we will intercept the responses of unauthorized requests to the server,
before they get back to the caller. We will suspend the current flow of the
application business logic, do the authentication, and then retry the failed requests
to resume the flow.


User Client App Server

Authenticate
OK
Retry Item
Request
Item Data

View Item
Show Login

Request Item
Data
Auth Error

Login

Show Item

Intercepting responses


Remember that the $http requests return promises, which are resolved with
the response from the server. The power of promises is that we can chain them,
transform the response data that is returned, and even return a promise to a
completely different deferred object. As described in Chapter 3, Communicating with
a Back-end Server, AngularJS lets you create interceptors that can work with the server
response, before it is received by the original caller.


HTTP response interceptors

A response interceptor is simply a function that receives a promise object for a
response from the server, and then returns a promise object for the same. On each
$http request, the response promise object will be passed to each interceptor, in turn
giving them each an opportunity to modify the promise object, before it is returned
to the original caller.


Generally, an interceptor function will use a call to then() to chain handlers onto the
promise object it is passed, and then creates a new promise, which it then returns.
Inside these handlers, we can read and modify the response object, such as the
headers and data, as shown in the following example:


function myInterceptor(promise) {
return promise.then(function(response) {
Free download pdf