[英]Symfony2 voter issue
I've got a problem with my custom Voter. 我的自定义选民有问题。 If the user has a specific role (for ex. 'ROLE_USER'), the voter will let him do the action.
如果用户具有特定角色(例如“ ROLE_USER”),则投票者将让他执行操作。 I'll try to leave in vote method only ACCESS_DENIED , but without success.
我将尝试仅使用ACCESS_DENIED表决方法,但不会成功。 It seems that the symfony is ignoring my custom Voter
看来symfony忽略了我的自定义选民
ItemVoter.php 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 services.yml
security.access.item_voter:
class: 'Cvut\Fit\BiWt2\InventoryBundle\Security\Authorization\Voter\ItemVoter'
tags:
- { name: security.voter }
use in a controller 在控制器中使用
$item = $itemService->getItem($id);
$roles = $this->getUser()->getRoles();
if (false === $this->get('security.context')->isGranted($roles[0]->getRole(), $item)) {
throw new AccessDeniedException('Unauthorised access!');
}
Every user has only 1 role ( role[0] is guaranteed) 每个用户只有一个角色(保证角色[0] )
Might you missed to read the last section of the Specific Voter documentation: http://symfony.com/doc/current/cookbook/security/voters.html#changing-the-access-decision-strategy Changing the Access Decision Strategy . 您可能错过了阅读《特定选民》文档的最后一部分: http : //symfony.com/doc/current/cookbook/security/voters.html#changing-the-access-decision-strategy 更改访问决策策略 。
This code in your security.yml file: 您的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
Has to solve your problem, and activate ItemVoter. 必须解决您的问题,并激活ItemVoter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.