简体   繁体   English

Symfony4/Twig - is_granted() 只检查角色数组中的第一个角色

[英]Symfony4/Twig - is_granted() only checks first role in an array of roles

I'm having trouble with checking permissions in Twig.我在 Twig 中检查权限时遇到问题。
Users can have multiple roles and they're stored in the DB as an array of strings.用户可以有多个角色,它们作为字符串数组存储在数据库中。 Some roles do not have access to the profile view.某些角色无权访问个人资料视图。
When I create a user who's one role allows to view the profile, but the other one doesn't - is_granted() seems to only check the first role in the array and returns false, even though the second role does allow access.当我创建一个角色允许查看个人资料但另一个角色不允许的用户时 - is_granted() 似乎只检查数组中的第一个角色并返回 false,即使第二个角色确实允许访问。

In the template it looks something like this:在模板中它看起来像这样:

{% if is_granted('ROLE_backend_USER_Profile') %}
    <li>
        <a href="{{ path('admin_profile') }}">Profile</a>
    </li>
{% endif %}

Role hierarchy looks like this:角色层次结构如下所示:

ROLE_BACKEND_ADMIN:
    - ROLE_BACKEND_USER
    - ROLE_backend_USER_Profile
    - ROLE_backend_Post_addPost
    ... etc. ...
ROLE_BACKEND_OTHERTYPEOF_ADMIN:
    - ROLE_backend_Home_index
    - ROLE_backend_typeof_list
    - ROLE_backend_typeof_edit
    ... etc. ...

If I have a user with both of these roles - is_granted('ROLE_backend_USER_Profile') returns false, even though having the other role should allow him access.如果我有一个用户同时拥有这两个角色 - is_granted('ROLE_backend_USER_Profile') 返回 false,即使拥有另一个角色应该允许他访问。

This behavior is expected.这种行为是意料之中的。 As explained in the Symfony Docs (read "Hierarchical Roles" section):如 Symfony Docs 中所述(阅读“分层角色”部分):

The role_hierarchy values are static - you can't, for example, store the role hierarchy in a database. role_hierarchy 值是静态的 - 例如,您不能将角色层次结构存储在数据库中。 If you need that, create a custom security voter that looks for the user roles in the database.如果需要,请创建一个自定义安全投票者,以在数据库中查找用户角色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM