选民中的symfony2调用is_granted:如何避免无限循环?

时间:2014-12-08 21:20:50

标签: php security symfony containers symfony-security

我已经建立了一个选民,我需要在用户上调用is_granted。

在我的选民中注入security.authorization_checker服务时,我收到以下错误

  

CheckCircularReferencesPass.php中的ServiceCircularReferenceException   第69行:检测到服务“manager_voter”的循环引用,   路径:“manager_voter - > security.authorization_checker - >   security.access.decision_manager - > manager_voter”。

没有其他方法可以注入整个容器吗?这是正常的吗?

编辑:

我正在呼叫控制者的选民:

    if (false === $this->get('security.authorization_checker')->isGranted('manage', $associate)) {
        throw new AccessDeniedException('Unauthorised access!');
    }

在这个选民中,我需要验证用户的角色:

if ($this->container->get('security.authorization_checker')->isGranted('ROLE_COMPANY_MANAGER'))
                {
                    return true;
                }

当然会导致循环。怎么不得到那个循环?如果我没有误会的话,在用户上调用$ user-> getRoles将不会考虑角色层次结构。

1 个答案:

答案 0 :(得分:0)

所以我找到答案归功于@Cerad:

精度:您无法扩展abstractVoter类,因为您需要访问令牌。只需实现抽象选民正在实施的相同界面。

Cerad命题:Symfony2 Custom Voter Role Hierarchy

我是:

<?php

namespace AppBundle\Security\Voter;

use AppBundle\Entity\User\Associate;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\User\UserInterface;

class ManagerVoter implements VoterInterface
{
    const SELECT_ASSOCIATES = 'select_associates';

    private $roleHierarchy;

    public function __construct(RoleHierarchy $roleHierarchy)
    {
        $this->roleHierarchy = $roleHierarchy;
    }

    protected function hasRole(TokenInterface $token, $targetRole)
    {
        $reachableRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
        foreach($reachableRoles as $role)
        {
            if ($role->getRole() == $targetRole) return true;
        }
        return false;
    }

    protected function getSupportedClasses()
    {
        return array(
            'AppBundle\Entity\User\Associate',
        );
    }

    protected function getSupportedAttributes()
    {
        return array(self::SELECT_ASSOCIATES);
    }

    /**
     * Iteratively check all given attributes by calling isGranted
     *
     * This method terminates as soon as it is able to return ACCESS_GRANTED
     * If at least one attribute is supported, but access not granted, then ACCESS_DENIED is returned
     * Otherwise it will return ACCESS_ABSTAIN
     *
     * @param TokenInterface $token      A TokenInterface instance
     * @param object         $object     The object to secure
     * @param array          $attributes An array of attributes associated with the method being invoked
     *
     * @return int     either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED
     */
    public function vote(TokenInterface $token, $object, array $attributes)
    {
        if (!$object || !$this->supportsClass(get_class($object))) {
            return self::ACCESS_ABSTAIN;
        }

        // abstain vote by default in case none of the attributes are supported
        $vote = self::ACCESS_ABSTAIN;

        foreach ($attributes as $attribute) {
            if (!$this->supportsAttribute($attribute)) {
                continue;
            }

            // as soon as at least one attribute is supported, default is to deny access
            $vote = self::ACCESS_DENIED;

            if ($this->isGranted($attribute, $object, $token)) {
                // grant access as soon as at least one voter returns a positive response
                return self::ACCESS_GRANTED;
            }
        }

        return $vote;
    }


    /**
     * Perform a single access check operation on a given attribute, object and (optionally) user
     * It is safe to assume that $attribute and $object's class pass supportsAttribute/supportsClass
     * $user can be one of the following:
     *   a UserInterface object (fully authenticated user)
     *   a string               (anonymously authenticated user)
     *
     * @param string $attribute
     * @param object $object
     * @param $token
     * @internal param string|UserInterface $user
     *
     * @return bool
     */
    protected function isGranted($attribute, $object, TokenInterface $token)
    {
        $user = $token->getUser();
        /** @var $object Associate */
        $associateRoles = $object->getRoles();

        // make sure there is a user object (i.e. that the user is logged in)
        if (!$user instanceof UserInterface) {
            return false;
        }

//        if ($this->hasRole($token, 'ROLE_ADMIN'))
//        {
//            return true;
//        }

        if ($attribute == self::SELECT_ASSOCIATES) {

            if (in_array('ROLE_COMPANY_STAFF',$associateRoles))
            {
                if ($this->hasRole($token, 'ROLE_COMPANY_MANAGER'))
                {
                    return true;
                }
            }
            elseif (in_array('ROLE_BOUTIQUE_STAFF',$associateRoles))
            {
                if ($this->hasRole($token, 'ROLE_BOUTIQUE_MANAGER'))
                {
                    return true;
                }
            }
            elseif (in_array('ROLE_SCHOOL_STAFF',$associateRoles))
            {
                if ($this->hasRole($token, 'ROLE_PROFESSOR'))
                {
                    return true;
                }
            }
        }

        return false;
    }


    /**
     * {@inheritdoc}
     */
    public function supportsAttribute($attribute)
    {
        return in_array($attribute, $this->getSupportedAttributes());
    }

    /**
     * {@inheritdoc}
     */
    public function supportsClass($class)
    {
        foreach ($this->getSupportedClasses() as $supportedClass) {
            if ($supportedClass === $class || is_subclass_of($class, $supportedClass)) {
                return true;
            }
        }

        return false;
    }
}