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

前端 未结 2 1126
无人及你
无人及你 2020-12-25 09:22

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 09:48

    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.

提交回复
热议问题