Skip to content

Security Voter not aware of role hierarchy in Symfony Best Practises #4389

Closed
@richard-keller

Description

@richard-keller

The section on Security suggests using Security Voters to implement complex security logic. The provided code example makes use of the getRoles() function to determine whether the user has the given role. However, it should be noted that this won't work if role hierarchies are used, since the User entity is not aware of the full role hierarchy.

Code snippet in question:

protected function isGranted($attribute, $post, $user = null)
{
    if ($attribute == self::CREATE && in_array(ROLE_ADMIN, $user->getRoles())) {
      return true;
    }

    return false;
}

I imagine that the best way to handle this would be to use something like $securityContext->isGranted('ROLE_ADMIN') but then we should be injecting security.context, and not the User.

Edit: It would appear that using security.context isn't a great idea, since it works using the token for the currently logged-in user. Regardless, I think the documentation should note that the solution provided will not work for hierarchical role structures.

Metadata

Metadata

Assignees

No one assigned

    Labels

    actionableClear and specific issues ready for anyone to take them.hasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions