我在确定如何为我们的 Angular 应用程序添加权限/访问控制时遇到了很多麻烦。现在我们有这个:
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('default', {
url: '',
templateUrl: 'pages/home/view/home.html',
controller: 'HomeCtrl'
})
.state('home', {
url: '/home',
templateUrl: 'pages/home/view/home.html',
controller: 'HomeCtrl',
permissions: { // ?
only: ['Admin','Moderator']
},
access: { // ?
roles: ['*']
},
resolve: { // ?
authenticate: function($state, $q, $timeout){
},
}
})
}]);
我在确定使用哪种方法来创建对每个页面的访问控制时遇到问题。
现在,登录用户存储在角度值中:
app.value('USER', JSON.parse('{{{user}}}'));
USER 值包含有关用户具有哪些角色/权限的信息。
但是我无法将 USER 注入回调app.config()
它说"未知提供者"。
如何根据用户参数进行访问控制?
执行的关键是在事件$stateChangeStart上添加访问控制
例如,如果您有这样的路由:
.state('termsofuse', {
url: "/terms",
templateUrl: "termOfUse.html",
resolve: {
authorizedRoles: function() {
return [USER_ROLES['su'],
USER_ROLES['user'],
USER_ROLES['admin'],
USER_ROLES['skysu']
]
}
}
})
您可以像这样定义您的访问控制
.run(
function($rootScope, $q, $location, $window, $timeout) {
$rootScope.$on(
'$stateChangeStart',
function(event, next, current) {
var authorizedRoles = next.resolve.authorizedRoles();
//this function controls if user has necessary roles
if (!isAuthorized(authorizedRoles)) {
event.preventDefault();
// and I broadcast the news $rootScope.$broadcast("AUTH_EVENTS.notAuthenticated");
} else {
$rootScope.$broadcast("AUTH_EVENTS.loginSuccess");
}
})
});
然后,您只需定义事件的捕获器来管理所需的行为(重定向/错误消息或任何必要的(
你可能想看看ngAA,我把它和ui-router一起使用。
这就是我让它工作的方式。我不确定这是否是最好的方法,但它确实有效。
您不能在 app.config(( 中注入服务/值,但可以将服务/值注入到 resolve.authenticate 函数中。
我决定使用 resolve.authenticate 方法。
.state('home', {
url: '/home',
templateUrl: 'pages/home/view/home.html',
controller: 'HomeCtrl',
resolve: {
authenticate: handlePageRequest['home'] // <<<<
}
})
然后我们有一个处理程序:
let handlePageRequest = {
'default': function ($q, USER, $state, $timeout, AuthService) {
// this page is always ok to access
return $q.when();
},
'home': function ($q, USER, $state, $timeout, AuthService) {
if(AuthService.isHomePageAccessible(USER)){
return $q.when();
}
else{
$timeout(function () {
$state.go('not-found'); // we can prevent user from accessing home page this way
}, 100);
return $q.reject()
}
},
};