12

我刚刚开始使用AngularJS我正在开发的应用程序,一切进展顺利,但我需要一种保护路线的方法,这样如果没有登录,用户就不会被允许去那条路线。我了解在服务方面也有保护,我会照顾好这个。

我发现了多种保护客户端的方法,一种似乎使用以下方法

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

我需要把这个放在.run哪里app.js

我发现的另一种方法是使用指令并使用 on - routechagestart

信息在这里 http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

我真的会对任何人对推荐方式的帮助和反馈感兴趣。

4

2 回答 2

23

使用 resolves 应该可以帮助你:(代码未测试)

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');
            }
        }
    }
});
于 2013-06-20T09:25:46.880 回答
4

resolve使用属性的另一种方式$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"
  });

}]);

这样,如果Access没有解决承诺,$routeChangeError事件将被触发:

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");
    }
  });

}]);

请参阅此答案的完整代码。

于 2015-04-22T15:47:32.280 回答