Chapter 7
This is not a security feature. It is really just a way to help users to
authenticate correctly, if they navigate directly to a URL that requires
some authorization.
Using route resolve functions
Each route defined with the $routeProvider service provider can contain a
set of route resolve functions. Each of these is a function that returns a promise
object, which must be resolved before navigation to the route can succeed. If any
of the promise object is rejected, then navigation to that route is cancelled.
A very simple approach to authorization would be to provide a route
resolve function that only resolves successfully if the current user has the
necessary authorization.
$routeProvider.when('/admin/users', {
resolve: [security, function requireAdminUser(security) {
var promise = service.requestCurrentUser();
return promise.then(function(currentUser) {
if ( !currentUser.isAdmin() ) {
return $q.reject();
}
return currentUser;
});
}]
});
Here, we request a promise for the current user from the security service, and
then reject it if the user is not an administrator. The trouble with this method is
that the user is not given an opportunity to log in and provide authorization.
The route is just blocked.
In the same way that we dealt with HTTP 401 authorization errors from the server,
we can also retry authorization failures, when navigating to a route. All we need
is to add a retry item to the securityRetryQueue service, whenever such a route
resolve fails, which will attempt the resolve again, once the user has logged in.
function requireAdminUser(security, securityRetryQueue) {
var promise = security.requestCurrentUser();
return promise.then(function(currentUser) {
if ( !currentUser.isAdmin() ) {
return securityRetryQueue.pushRetryFn(
'unauthorized-client',