我在确定如何向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){
},
}
})
}]);
我无法确定使用哪种方法为每个页面创建访问控制。
现在,登录用户存储在Angular值中:
app.value('USER', JSON.parse('{{{user}}}'));
USER值包含有关用户具有哪些角色/权限的信息。
但我无法将USER注入app.config()
回调,它说“未知提供商”。
如何根据USER参数进行访问控制?
答案 0 :(得分:3)
执行此操作的关键是在事件$ stateChangeStart
上添加访问控制例如,如果你有这样的路由:
.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");
}
})
});
你可以像那样定义你的访问控制
sub
然后,您只需定义事件的捕获器以管理所需的行为(重定向/错误消息或任何必要的行为)
答案 1 :(得分:2)
您可能需要查看ngAA,我将它与ui-router一起使用。
答案 2 :(得分:0)
这就是我开始工作的方式。我不确定它是否是最好的方式,但确实有效。
您无法在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()
}
},
};