Symfony 2 – How-to check user’s role in Voter

How-to make sure in a Voter that a user has the right role in the Symfony role hierarchy.

first, two links. One to the Symfony 2 Voter’s documentation, and the second to the Access Decision Manager’s documentation.

We will see here, how to check if the current user has the right role in the roles’s hierarchy.

In a first time we have to add a service to the Voter declaration DI. We need to use the “security.access.role_hierarchy_voter” service.

Your declaration, must look like that.

<service id="security.voter.categorie" class="MyBundle\Security\Authorization\Voter\CategorieVoter" public="false">
   <argument type="service" id="security.access.role_hierarchy_voter" />
   <tag name="security.voter" />
</service>

In your Voter class you have to retrieve the service. We just need to add a new attribute, like the code below.

namespace MyBundle\Security\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class CategorieVoter implements VoterInterface
{
    /**
     * @var \Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter
     */
    private $roleVoter;

    public function __construct($roleVoter)
    {
            $this->roleVoter = $roleVoter;
    }
//...
}

The use of this service is pretty easy.

if($this->roleVoter->vote($token, $token->getUser(), array('ROLE_USER')) === VoterInterface::ACCESS_GRANTED) {
      // The user has the right role
}

So, now, if the current user has the role ROLE_ADMIN, according to the hierarchy of roles, he has ROLE_USER to, so the voter method return a VoterInterface::ACCESS_GRANTED

2 comments on “Symfony 2 – How-to check user’s role in Voter
  1. Vladimir Popov says:

    What if result is “ACCESS_DENIED”?
    -1 will also result true in condition.

Leave a Reply

Your email address will not be published. Required fields are marked *

*