Symfony Voter不断使用

时间:2017-07-04 12:59:36

标签: php symfony security constants symfony2-voter

我定义了一个选民,尤其是voteOnAttribute方法,如下所示:

 public function voteOnAttribute($attributes, $subject, TokenInterface $token) {

        $user = $token->getUser();

        if (!$user instanceof User) {
            return false;
            // return static::ACCESS_DENIED
        }
        if(!$subject instanceof PrivateResource) {
            throw new Exception('Media type mismatch : private resource expected here');
        }

        // Check company is elligible here
        if(!$subject->getCompanies()->contains($user->getCompany())){
            return false;
            // return static::ACCESS_DENIED
        }

        return static::ACCESS_GRANTED;
    }

为什么我不能在我的方法中使用VoterInterface常量(ACCESS_GRANTEDACCESS_ABSTAINACCESS_DENIED)?

如果我这样做,则由于抽象类vote中的方法Voter而未强制执行拒绝访问决定:

public function vote(TokenInterface $token, $subject, array $attributes)
    {
        // abstain vote by default in case none of the attributes are supported
        $vote = self::ACCESS_ABSTAIN;

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

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

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

        return $vote;
    }

由于ACCESS_DENIED常量在VoterInterface中设置为-1,if ($this->voteOnAttribute($attribute, $subject, $token))条件为真,即使返回为-1。

我在这里误会了什么?这些常量是否计划用于我们的自定义voteOnAttribute方法?

注意:我将选民策略设置为unanimous

中的security.yml

1 个答案:

答案 0 :(得分:2)

首先,我认为我错过了对文档的理解。

但是symfony版本之间的文档存在差异

假设您正在使用symfony> = 2.7,您应该在voteOnAttribute中返回布尔值