简体   繁体   中英

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

I'm having trouble with checking permissions in 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.

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.

This behavior is expected. As explained in the Symfony Docs (read "Hierarchical Roles" section):

The role_hierarchy values are static - you can't, for example, store the role hierarchy in a database. If you need that, create a custom security voter that looks for the user roles in the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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