Angular UI路由器:1过渡身份验证,授权和基于角色的检查

时间:2018-05-14 11:14:44

标签: angularjs angular-ui-router

我在我的应用中使用新的ui-router 1.0.3。我需要在我的应用程序中实现身份验证和授权。这是我的代码

   run(function ($transitions, $state, AuthService) {
    $transitions.onStart({
      to: function (state) {
        return !!(state.data && state.data.requiredAuth);
      }
    }, function (state) {
      if (!AuthService.isAuthenticated()) {
        return $state.target('auth.login');
      }
    }
    );
    $transitions.onStart({
      to: 'auth.*'
    }, function () {
      if (AuthService.isAuthenticated()) {
        return $state.target('app');
      }
    });
  });

这是我的配置

  .config(function ($stateProvider,$urlRouterProvider) {
    $stateProvider
    .state('app', {
      redirectTo: 'contacts',
      url: '/app',
      data: {
        requiredAuth: true,
      },
      component: 'app'
    })
    .state('contacts', {
      parent: 'app',
      url: '/contacts?filter',
      component: 'contacts',
      params: {
        filter: {
          value: 'none'
        }
      },
      data :{
        role : ['Admin','Manager'],
        permission : 'read'
      },
      resolve: {
        contacts: function (ContactService) {
          return ContactService.getContactList().$loaded();
        },
        filter: function ($transition$) {
          return $transition$.params();
        }
      }
    })
    .state('contact', {
      parent: 'app',
      url: '/contact/:id',
      component: 'contactEdit',
      data :{
        role : ['Admin','Manager'],
        permission : 'edit'
      },
      resolve: {
        contact: function ($transition$, ContactService) {
          var key = $transition$.params().id;
          return ContactService.getContactById(key).$loaded();
        }
      }
    })
    .state('auth.register', {
      url: '/register',
      component: 'register'
    })
    .state('auth', {
      redirectTo: 'auth.login',
      url: '/auth',
      template: '<div ui-view></div>'
    })
    .state('auth.login', {
      url: '/login',
      component: 'login'
    })
    .state('auth.denied',{
      url:'/denied',
      component:'accessDenied'
    });
  $urlRouterProvider.otherwise('/auth/login');
  });

这是服务功能

this.isAuthenticated = function () {
    return !!authData;
  };

当我登录时,它成功处理身份验证并将我发送到联系状态。当我退出并直接访问联系页面时,它停留在登录页面上。我需要检查角色和权限的状态数据。

需要帮助。

0 个答案:

没有答案