I have just started out working with an AngularJS
app I\'m developing, everything is going well but I need a way of protecting routes so that a user wouldn\'t b
Using resolves should help you out here: (code not tested)
angular.module('app' []).config(function($routeProvider){
$routeProvider
.when('/needsauthorisation', {
//config for controller and template
resolve : {
//This function is injected with the AuthService where you'll put your authentication logic
'auth' : function(AuthService){
return AuthService.authenticate();
}
}
});
}).run(function($rootScope, $location){
//If the route change failed due to authentication error, redirect them out
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
if(rejection === 'Not Authenticated'){
$location.path('/');
}
})
}).factory('AuthService', function($q){
return {
authenticate : function(){
//Authentication logic here
if(isAuthenticated){
//If authenticated, return anything you want, probably a user object
return true;
} else {
//Else send a rejection
return $q.reject('Not Authenticated');
}
}
}
});
Another way of using the resolve
attribute of the $routeProvider
:
angular.config(["$routeProvider",
function($routeProvider) {
"use strict";
$routeProvider
.when("/forbidden", {
/* ... */
})
.when("/signin", {
/* ... */
resolve: {
access: ["Access", function(Access) { return Access.isAnonymous(); }],
}
})
.when("/home", {
/* ... */
resolve: {
access: ["Access", function(Access) { return Access.isAuthenticated(); }],
}
})
.when("/admin", {
/* ... */
resolve: {
access: ["Access", function(Access) { return Access.hasRole("ADMIN"); }],
}
})
.otherwise({
redirectTo: "/home"
});
}]);
This way, if Access
does not resolve the promise, the $routeChangeError
event will be fired:
angular.run(["$rootScope", "Access", "$location",
function($rootScope, Access, $location) {
"use strict";
$rootScope.$on("$routeChangeError", function(event, current, previous, rejection) {
if (rejection == Access.UNAUTHORIZED) {
$location.path("/login");
} else if (rejection == Access.FORBIDDEN) {
$location.path("/forbidden");
}
});
}]);
See the full code on this answer.