Symfony2选民问题

时间:2014-06-02 11:32:28

标签: php symfony authorization

我的自定义选民有问题。如果用户具有特定角色(例如'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] 有保证)

1 个答案:

答案 0 :(得分:2)

你可能错过了阅读特定选民文件的最后一部分: 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。