0
votes

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.

1
roles in symfony can be tricky, in fact very tricky. use the profiler to see which roles the security token has, those roles may very much NOT match the user's roles that you may expect. logging out and back in may very well change the security token's roles. (this is sometimes relevant and practical for impersonating users, it provides the security token (not the user) with a role, that communicates to the framework, that it's an impersonation and stuff). so please check the profiler to see which roles the security token has (it's the only relevant thing for is_granted('ROLE_...')) - Jakumi
I'll try this and report back. - Pirate

1 Answers

3
votes

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.