Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Protecting routes with angularjs depending if the user is authorized?

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 be allowed to go to that route if not logged in. I understand the importance of protecting on the service side also and I will be taking care of this.

I have found a number of ways of protecting the client, one seems to use the following

$scope.$watch(
    function() {
        return $location.path();
    },
    function(newValue, oldValue) {
        if ($scope.loggedIn == false && newValue != '/login') {
            $location.path('/login');
        }
    }
);

where do I need to put this, in the .run in the app.js?

And the other way I have found is using a directive and using an on - routechagestart

the info is here http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

I would really be interested in anyones help and feedback on the recommended way.

like image 789
Martin Avatar asked Jun 20 '13 08:06

Martin


People also ask

What makes route path case sensitive in AngularJS routes?

That's because the routes that are configured using UI-Router are case sensitive. To make route insensitive, all you have to do is to inject $urlMatcherFactoryProvider service into the config() function and call caseInsensitive(true) function. Let's go back to our Controller.

What is authentication in AngularJS?

Authentication plays an important role in today's web applications. It is a process of accessing application or features by providing user's identity that helps the verifier in getting complete information about the user's activity. We can categorize the web-applications into 2 types – Public & Private.

How does AngularJS route work?

AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire application. Important: $routeProvider is used to configure the routes.

What is the use of $state in AngularJS?

$stateProvider is used to define different states of one route. You can give the state a name, different controller, different view without having to use a direct href to a route. There are different methods that use the concept of $stateprovider in AngularJS.


2 Answers

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');
            }
        }
    }
});
like image 150
Clark Pan Avatar answered Sep 19 '22 17:09

Clark Pan


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.

like image 30
sp00m Avatar answered Sep 21 '22 17:09

sp00m