首页 > 解决方案 > 具有角色数组的 Twig is_granted()

问题描述

我试图将一个数组传递给 is_granted() 树枝过滤器但不起作用,尽管在文档中说是: https ://symfony.com/doc/current/reference/twig_reference.html#is-granted

想象一下 app.user 具有角色 ROLE_MANAGER。

例子:

{{ dump(is_granted('ROLE_MANAGER')) }}

这返回:

{{ dump(is_granted(['ROLE_ADMIN','ROLE_MANAGER'])) }}

这返回:

文件说:

角色:类型:字符串,字符串[]

如果当前用户具有给定角色,则返回 true。如果在一个数组中传递了多个角色,如果用户至少拥有其中一个,则返回 true。

但这不起作用......知道为什么吗?

标签: symfony

解决方案


我遇到过同样的问题。我通过创建自定义选民解决了这个问题。出于某种原因,is_granted 函数不能像文档所说的那样工作。检查代码我注意到它从来没有为这个案例找到一个投票者,这就是我最终创建一个投票者的原因。

下面是我使用的选民示例:

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
    class MenuVoter extends Voter
    {

        /**
         *
         * @var Security
         */
        private $security;

        public function __construct(Security $security)
        {
            $this->security = $security;
        }

        /**
         * {@inheritdoc}
         */
        protected function supports($attribute, $subject): bool
        {
            return $subject === null && \is_array($attribute);
        }

        /**
         * {@inheritdoc}
         */
        protected function voteOnAttribute($attributes, $post, TokenInterface $token): bool
        {
            $user = $token->getUser();
            $r = false;

            if (!($user instanceof UserInterface)) {
                return false;
            }

            foreach ($attributes as $attribute) {
                if ($this->security->isGranted($attribute)) {
                    $r = true;
                    break;
                }
            }

            return $r;
        }

    }

它的基本作用是遍历每个角色(属性)并检查是否授予其中一个访问权限。

我希望它有所帮助,如果有人有更好的方法,我很想知道。


推荐阅读