我定义了一个选民,尤其是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_GRANTED
,ACCESS_ABSTAIN
,ACCESS_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
答案 0 :(得分:2)
首先,我认为我错过了对文档的理解。
但是symfony版本之间的文档存在差异
扩展Voter或实施VoterInterface
返回true或false
https://symfony.com/doc/current/security/voters.html
实现VoterInterface
返回常量ACCESS_ *
过时的symfony> 2.5
https://symfony.com/doc/2.4/cookbook/security/voters_data_permission.html
假设您正在使用symfony> = 2.7,您应该在voteOnAttribute中返回布尔值