【问题标题】:AngularJS: Protecting routes with angularjs depending if the user is authorized?AngularJS:根据用户是否获得授权,使用 angularjs 保护路由?
【发布时间】:2013-06-17 01:09:03
【问题描述】:

我刚刚开始使用我正在开发的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

我真的很想知道任何人对推荐方式的帮助和反馈。

【问题讨论】:

  • egghead.io(免费)视频 27->39 解释了整个路由。它应该可以帮助你。最接近的视频是 Resolve (35)
  • 谢谢 Utopik,是的,我已经看过了。我想我真的在寻找一些关于上述推荐方式的意见。

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

使用解析应该可以帮助您:(代码未测试)

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

【讨论】:

  • 谢谢,所以如果没有经过身份验证,我会在哪里做 $location.path ?重定向
  • 您可以通过在路由失败时针对路由范围广播的 $routeChangeError 事件来做到这一点。我会更新我的答案
  • 有没有办法在全球范围内为所有路线执行此操作?
  • -1 - 问题专门关于授权,而不是身份验证。我会使用路由/状态更改事件。将所需的“角色”添加到路由提供者数据(自定义属性)并在事件中进行测试
【解决方案2】:

$routeProviderresolve属性的另一种使用方式:

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 没有解决promise,$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");
    }
  });

}]);

this answer上查看完整代码。

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2015-09-10
    • 2019-05-17
    • 2019-01-05
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多