【问题标题】:Authenticate on stateProvider for a specific user (angular-fullstack)在 stateProvider 上为特定用户进行身份验证(angular-fullstack)
【发布时间】:2016-07-07 23:22:33
【问题描述】:

我为我的项目使用 angular-fullstack 生成器 (https://github.com/angular-fullstack/generator-angular-fullstack),并且我的网站上有一个需求页面,需要具有定义角色的用户访问 (admin)。 此页面还需要可供创建需求的用户访问。

我知道我可以将 authenticate:true 放在我的状态提供程序上以仅授权经过身份验证的用户,但我需要一个更精确的系统来适应我的情况,因为我只需要允许具有特定角色或特定用户 ID 的用户。

有没有办法在 stateProvider 中管理这种情况,或者我必须在我的页面控制器中这样做,在 $state 重定向之后?

感谢您的宝贵时间

【问题讨论】:

    标签: javascript angularjs angular-ui-router angular-fullstack


    【解决方案1】:

    可以对特定的role进行授权,但需要修改一些代码。

    将新字段access 添加到您的state 配置文件中,如下所示。让我们将authRequiredFor 数组存储在其中包含需要授权才能访问特定状态myState 的角色。

    angular.module('myApp')
        .config(function ($stateProvider) {
        $stateProvider
          .state('myState', {
            url: '...',
            templateUrl: '...',
            controller: '...',
            access: {
                authRequiredFor: ['role1', 'role2']
            }                
        });
    });
    

    在你的app.js文件的run()函数中,你需要添加和修改$stateChangeStart回调函数来检查用户在访问任何状态之前是否需要认证。

    .run(function ($rootScope, $location, Auth, $state) {
        // Redirect to login if route requires auth and you're not logged in
        $rootScope.$on('$stateChangeStart', function (event, next) {
            Auth.isLoggedInAsync(function(loggedIn) {
                if (next.authenticate && !loggedIn) {
                    $location.url('/login');
                }
                if (next.access) {  // check if the state config contains the field `access`
                    var permissions = next.access;
                    var userRole = Auth.getCurrentUser().role;
                    if (permissions.authRequiredFor) {
                        // check if the logged in user's role matches with the roles in the array
                        if (permissions.authRequiredFor.indexOf(userRole) >= 0) {
                            $location.url('/login'); // or redirect him to some other url/state
                        }
                    }
                }        
            });
        });
    });
    

    希望这能解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2016-03-04
      • 2015-02-11
      • 1970-01-01
      • 2013-03-11
      相关资源
      最近更新 更多