[英]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.