-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Security Voter not aware of role hierarchy in Symfony Best Practises #4389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
So it turns out that injecting Update: the following does not work. The following is a Inject the Service Container into the voter via the constructor:
The the voter class would look something like this: class CustomVoter extends AbstractVoter
{
const DELETE = 'delete';
private $roles;
function __construct(ContainerInterface $container)
{
$this->roles = array_keys($container->getParameter('security.role_hierarchy.roles'));
}
protected function isGranted($attribute, $object, $user = null)
{
if (!$user instanceof UserInterface)
{
return false;
}
if ($attribute == self::DELETE)
{
if (in_array('ROLE_USER', $this->roles))
return true;
}
return false;
}
} |
@richard-keller Your code always returns |
First inject @security.role_hierarchy into the voter. Then use this code:
|
If I understand things correctly, this can't be fixed at the moment. @javiereguiluz can you please confirm? |
@wouterj sadly this problem cannot be solved yet. There is a pending PR symfony/symfony#14048 which unfortunately didn't get much attention. |
See symfony/symfony#14048 (comment) - this is now actionable in 2.8 and we really should have a cookbook article or section about this. |
Fixed! |
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:
I imagine that the best way to handle this would be to use something like
$securityContext->isGranted('ROLE_ADMIN')
but then we should be injectingsecurity.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.The text was updated successfully, but these errors were encountered: