角色不是特定于 FOSUserBundle 的。他们在 Symfony 中。
ACLs http://symfony.com/doc/current/cookbook/security/acl.html比使用角色更复杂。所以我建议使用角色。
来自 Symfony 文档:
ACL 的替代方案
使用 ACL 并不简单,对于更简单的用例,它可能是
矫枉过正。如果你的权限逻辑可以通过写来描述
一些代码(例如,检查博客是否由当前用户拥有),然后
考虑使用选民。投票者被传递了被投票的对象,
您可以用它来做出复杂的决策并有效地实施
您自己的 ACL。强制授权(例如 isGranted 部分)将
看起来与您在本条目中看到的类似,但您的选民类别将
处理幕后的逻辑,而不是 ACL 系统。
要处理“权限”,我建议使用Voters http://symfony.com/doc/current/cookbook/security/voters.html :
首先创建一个像这样的选民:
配置 :
# app/config/services.yml
services:
app.user_permissions:
class: AppBundle\Voters\UserPermissionsVoter
arguments: ['@security.access.decision_manager']
tags:
- { name: security.voter }
public: false
和班级:
namespace AppBundle\Voters;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class UserPermissionsVoter extends Voter
{
const USER_CREATE = 'user_create';
const USER_EDIT = 'user_edit';
const USER_DELETE = 'user_delete';
private $decisionManager;
public function __construct($decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $object)
{
if (!in_array($attribute, array(self::USER_CREATE,self::USER_EDIT,self::USER_DELETE))) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $object, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch($attribute) {
case self::USER_CREATE:
if ($this->decisionManager->decide($token, array('ROLE_USER_MANAGEMENT_WITH_DELETE'))
|| $this->decisionManager->decide($token, array('USER_MANAGEMENT_WITHOUT_DELETE'))
){
return true;
}
break;
case self::USER_EDIT:
// ...
break;
case self::USER_DELETE:
// ...
break;
}
return false;
}
}
然后您可以检查控制器中的权限:
userCreateAction()
{
if(!$this->isGranted('user_create')){throw $this->createAccessDeniedException('You are not allowed to create an user.');}
// next steps ...
}