Description
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.