php – 管理角色并为角色分配权限 – Symfony
作者:互联网
我正在Symfony 3中构建一个基于Roles& amp ;;的管理面板.权限.将为每个管理员分配一个角色(或多个角色),然后他将能够根据分配给该角色的权限执行操作.
为了给你一个想法,这是一个例子:
>管理面板具有添加用户,编辑用户和删除用户的功能.
>我创建了一个角色:USER_MANAGEMENT_WITHOUT_DELETE,它具有user_create和user_edit的权限.
>我创建了USER_MANAGEMENT_WITH_DELETE角色,该角色具有user_create,user_edit和user_delete的权限
>现在,具有角色USER_MANAGEMENT_WITH_DELETE的管理员可以添加,编辑和删除用户,其中具有角色USER_MANAGEMENT_WITHOUT_DELETE的管理员只能添加和编辑用户但不能删除它们.
我搜索并发现了大约FOSUserBundle和ACL.有些recommended ACL而其他人说它对use FOSUserBunder更好
我还阅读了FOSUserBunder的文档以及它如何在角色列中存储角色,类似于:1:{i:0; s:10:“ROLE_ADMIN”;},但没有提到任何关于权限的内容.所以这是我的疑问:
>我在两者之间感到困惑.我应该使用哪一个?
>如果我使用FOSUserBunder,如何管理权限?
解决方法:
角色不是特定的tu FOSUserBundle.他们在Symfony.
ACLs比使用角色更复杂.所以我建议使用角色.
从Symfony文档中:
ACL的替代品
Using ACL’s isn’t trivial, and for simpler use cases, it may be
overkill. If your permission logic could be described by just writing
some code (e.g. to check if a Blog is owned by the current User), then
consider using voters. A voter is passed the object being voted on,
which you can use to make complex decisions and effectively implement
your own ACL. Enforcing authorization (e.g. the isGranted part) will
look similar to what you see in this entry, but your voter class will
handle the logic behind the scenes, instead of the ACL system.
要处理’权限’,我建议使用Voters:
首先创建一个这样的选民:
配置:
# 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 ...
}
标签:php,permissions,fosuserbundle,symfony,acl 来源: https://codeday.me/bug/20190608/1199582.html