Symfony 2.1 - $this->get('security.context')->isGranted('ROLE_ADMIN') returns false even if Profiler says I have that role

symfony-2.1

Solution

Finally got it. A dim idea hit my mind a minute ago. The problem was caused my own `RoleHierarchyInterface` implementation. My original idea was to copy Symfony's own, but load it from the ORM instead of `security.yml`. But because of this, I had to totally rewrite the `buildRoleMap()` function. The diff is as follows:

 private function buildRoleMap()
 {
     $this->map = array();
     $roles = $this->roleRepo->findAll();
     foreach ($roles as $mainRole) {
         $main = $mainRole->getRole();
 -       $this->map[$main] = array();
 +       $this->map[$main] = array($main);
         foreach ($mainRole->getInheritedRoles() as $childRole) {
             $this->map[$main][] = $childRole->getRole();
             // TODO: This is one-level only. Get as deep as possible.
             // BEWARE OF RECURSIVE NESTING!
             foreach ($childRole->getInheritedRoles() as $grandchildRole) {
                 $this->map[$main][] = $grandchildRole->getRole();
             }
         }
     }
 }

Problem

I have a Controller action (the Controller has `$this->securityContext` set to `$this->get('security.context')` via JMSDiExtraBundle): ``` $user = $this->securityContext->getToken()->getUser(); $groupRepo = $this->getDoctrine()->getRepository('KekRozsakFrontBundle:Group'); if ($this->securityContext->isGranted('ROLE_ADMIN') === false) { $myGroups = $groupRepo->findByLeader($user); } else { $myGroups = $groupRepo->findAll(); } ``` When I log in to the `dev` environment and check the profiler, I can see that I have the `ROLE_ADMIN` role granted, but I still get the filtered list of Groups. I have put some debugging code in my Controller, and Symfony's `RoleVoter.php`. The string representation of the Token in my Controller (`$this->securityContext->getToken()`) and the one in `RoleVoter.php` are the same, but when I use `$token->getRoles()`, I get two different arrays. My Users and Roles are stored in the database via the User and Role entities. Is this a bug that I found or am I doing something wrong?

Original source