[英]Symfony2 voter issue
我的自定义选民有问题。 如果用户具有特定角色(例如“ ROLE_USER”),则投票者将让他执行操作。 我将尝试仅使用ACCESS_DENIED表决方法,但不会成功。 看来symfony忽略了我的自定义选民
ItemVoter.php
class ItemVoter implements VoterInterface
{
const ROLE_ADMIN = 'ROLE_ADMIN';
const ROLE_MANAGER = 'ROLE_MANAGER';
const ROLE_USER = 'ROLE_USER';
public function supportsAttribute($attribute) {
return in_array($attribute, array(
self::ROLE_ADMIN,
self::ROLE_MANAGER,
self::ROLE_USER,
));
}
public function supportsClass($class) {
$supportedClass = 'Cvut\Fit\BiWt2\InventoryBundle\Entity\Item';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
public function vote(TokenInterface $token, $item, array $attributes) {
/*
if (!$this->supportsClass(get_class($item))) {
return VoterInterface::ACCESS_ABSTAIN;
}
$attribute = $attributes[0];
$user = $token->getUser();
if (!$this->supportsAttribute($attribute)) {
return VoterInterface::ACCESS_ABSTAIN;
}
*/
/*
switch($attribute) {
case 'ROLE_USER':
if($user->getId() === $item->getPerson()->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
break;
case 'ROLE_MANAGER':
if($user->getId === $item->getOrganizationalUnit()->getSuperiorUnit()) {
//return VoterInterface::ACCESS_GRANTED;
}
break;
case 'ROLE ADMIN':
//return VoterInterface::ACCESS_GRANTED;
break;
}*/
return VoterInterface::ACCESS_DENIED;
}
}
services.yml
security.access.item_voter:
class: 'Cvut\Fit\BiWt2\InventoryBundle\Security\Authorization\Voter\ItemVoter'
tags:
- { name: security.voter }
在控制器中使用
$item = $itemService->getItem($id);
$roles = $this->getUser()->getRoles();
if (false === $this->get('security.context')->isGranted($roles[0]->getRole(), $item)) {
throw new AccessDeniedException('Unauthorised access!');
}
每个用户只有一个角色(保证角色[0] )
您可能错过了阅读《特定选民》文档的最后一部分: http : //symfony.com/doc/current/cookbook/security/voters.html#changing-the-access-decision-strategy 更改访问决策策略 。
您的security.yml文件中的以下代码:
# app/config/security.yml
security:
access_decision_manager:
# strategy can be: affirmative, unanimous or consensus
strategy: unanimous
# only grant access if none of the voters has denied access
必须解决您的问题,并激活ItemVoter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.