1

我有一个在控制器中完美运行的 Voter,但是当我尝试在服务中使用它时,它总是返回 true,尽管它有一个“return false”语句。

我看到的唯一区别是我称呼它的方式。

在控制器中,我以这种方式使用它:

    $this->denyAccessUnlessGranted('ver', $menu);

在服务中,我这样称呼它:

    $this->authorizationChecker->isGranted('ver', $menu);

在服务中,我注入 AuthorizationChecker 并且它可以工作,但它似乎运行其他选民(我只有一个)。

在“security.yml”中我有这个:

    access_decision_manager:
        strategy: unanimous

选民代码:

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token){

    $usuario = $token->getUser();

    if (!$usuario instanceof Usuarios) {
        return false;
    }

    /** @var Menu $menu */
    $menu = $subject;


    switch ($attribute) {
        case self::VER:
            return false;
        case self::EDITAR:
            return false;
        case self::IMPRIMIR:
            return false;
    }

    throw new \LogicException('This code should not be reached!');
}

任何人都可以帮助我吗?

4

2 回答 2

1

好的,我找到了答案。

这之间的区别......:

    $this->denyAccessUnlessGranted('ver', $menu);

... 还有这个 ...:

    $this->authorizationChecker->isGranted('ver', $menu);

...是他们通知您结果的方式。

第一个语句抛出一个 DenyAccessException 但第二个语句返回一个布尔值(不要抛出异常)。

我没有意识到这一点:)

感谢大家的帮助。

于 2017-08-05T06:23:03.033 回答
0
    $this->denyAccessUnlessGranted('ver', $menu);

    $this->authorizationChecker->isGranted('ver', $menu);

会做同样的工作。

请检查$menu服务和控制器中的内容。

$this->denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')是一个捷径$this->container->get('security.authorization_checker')->isGranted($attributes, $object)

您的自定义选民需要实现 VoterInterface 或扩展选民,这使得创建选民更加容易。你是否 ?

检查官方文档以检查您的选民的良好实施。https://symfony.com/doc/current/security/voters.html

于 2017-08-01T09:29:32.540 回答