【问题标题】:AngularJS adding authorization to routesAngularJS向路由添加授权
【发布时间】:2015-09-10 07:14:03
【问题描述】:

如何向 AngularJS 和 ui.router 添加授权? 我正在使用 modulg ng-oauth https://github.com/andreareginato/oauth-ng

我可以使用页面http://andreareginato.github.io/oauth-ng/中的以下示例吗?

$scope.$on('oauth:login', function(event, token) {
  console.log('Authorized third party app with token', token.access_token);
});

$scope.$on('oauth:logout', function(event) {
  console.log('The user has signed out');
});

$scope.$on('oauth:loggedOut', function(event) {
  console.log('The user is not signed in');
});

$scope.$on('oauth:denied', function(event) {
  console.log('The user did not authorize the third party app');
});

$scope.$on('oauth:expired', function(event) {
  console.log('The access token is expired. Please refresh.');
});

$scope.$on('oauth:profile', function(profile) {
  console.log('User profile data retrieved: ', profile);
});

谢谢, 西蒙

【问题讨论】:

    标签: javascript angularjs oauth angular-ui-router


    【解决方案1】:

    你可以像这样创建一些常量角色:

    .constant('USER_ROLES', {
        ALL: '*', //@unused
        ADMIN: 'ROLE_ADMIN';
        USER: 'ROLE_USER',
        ANONYMOUS: 'ROLE_ANONYMOUS' 
    })
    

    将此自定义数据/常量添加到您的状态:

    $stateProvider.state('myapp.admin', {
        url: '/admin',
        .....
        data : {
            authorizedRoles : [USER_ROLES.ADMIN] //Thes
        }
    }
    

    因此,当您对这些角色进行身份验证并从数据库中检索这些角色时,您可以将其存储在您的用户对象和会话中,以便最终在路由更改时进行验证...

    在您的身份验证服务中(除了登录、注销等),您可以添加以下方法。

    isAuthenticated: function () {
        return session.hasSession();
    },
    
    isAuthorized: function (authorizedRoles) {
        if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
        }
    
        var roles = session.roles();
    
        var roleIncluded = roles.some(function (role) {
            return (authorizedRoles.indexOf(role) != -1);
        });
    
        return (session.hasSession() && roleIncluded);
    },
    

    因此,当您在应用程序.run 中更改路由时,会发生块验证并且可以进行预防。

    $rootScope.$on('$stateChangeStart', function (event, next) {
        if (authService.isAuthenticated()) {
            if (next.data.authorizedRoles === null) {
                handle();
            }
            if (!authService.isAuthorized(next.data.authorizedRoles)) {
                handle();
            }
        } else {
            handle();
        }
    }
    

    当然这只是一个例子,请记住还有其他解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多