Symfony 2 FOSUSER问题is_granted in twig

时间:2015-08-24 10:16:15

标签: symfony twig fosuserbundle

我在twig中遇到了is_granted('')函数的问题。 我当前的用户具有以下角色:['ROLE_USER','ROLE_FOOBAR'],从symfony探查器检查。

使用此代码:打印管理员链接(KO):

{% if is_granted('ROLE_BACKOFFICE') or is_granted('ROLE_SYSTEM') %}
<li>
    <a href="{{ path('sonata_admin_dashboard') }}">
       ADMIN
    </a>
</li>
{% endif %}

使用此代码:不打印管理员链接(确定):

{% if app.user.hasRole('ROLE_BACKOFFICE') or  app.user.hasRole('ROLE_SYSTEM') %}
<li>
    <a href="{{ path('sonata_admin_dashboard') }}">
       ADMIN
    </a>
</li>
{% endif %}

我不明白为什么用is_granted打印链接? 我的角色层次结构似乎没问题,该代码出了什么问题?

如果你看看vendor / friendsofsymfony / user-bundle / Model / User.php,它解释了在这种情况下不能使用hasRole:

  /**
     * Never use this to check if this user has access to anything!
     *
     * Use the SecurityContext, or an implementation of AccessDecisionManager
     * instead, e.g.
     *
     *         $securityContext->isGranted('ROLE_USER');
     *
     * @param string $role
     *
     * @return boolean
     */
    public function hasRole($role)
    {
        return in_array(strtoupper($role), $this->getRoles(), true);
    }

以下是security.yml:

中我的角色层次结构的片段
role_hierarchy:
    ROLE_FOOBAR:         ROLE_USER
...
    ROLE_ADMIN:         [ROLE_USER, ROLE_MANAGER]

1 个答案:

答案 0 :(得分:0)

我终于找到了问题: 问题来自选民内部的错误。我改变了这个片段:

 if (!$this->supportsClass(get_class($object))) {
        return self::ACCESS_ABSTAIN;
    }

到:

if

现在,一切都很好,再次。刚刚失去了我的一天!我希望这会有所帮助。