Get all roles from security.role_hierarchy

900 Views Asked by At

I am upgrading a Symfony application from v4 to v6.

I have a role_hierarchy defined in my security.yaml file, and want to return all of these roles in an API route, so admins can edit a user's roles on the frontend.

Anyway, this is the way I got those roles in v4.

  /**
   * Return all defined roles
   * @Rest\Get(path="/roles")
   * @Security("is_granted('ROLE_GLOBAL_ADMIN') or is_granted('ROLE_MAP_ADMIN')")
   */
  public function getRolesAction() : Response
  {
    $roles = $this->container->getParameter('security.role_hierarchy.roles');

    $serialized = $this->serializer->serialize($roles, 'json');
    return new Response($serialized, 200, array('Content-Type' => 'application/json'));
  }

I cannot seem to find the replacement for

$this->container->getParameter('security.role_hierarchy.roles');

in Symfony 6. If I change it to

$this->container->get('security.role_hierarchy.roles');

Service "security.role_hierarchy.roles" not found: the container inside "App\Controller\Api\Admin\UserController" is a smaller service locator that only knows about the "form.factory", "fos_rest.view_handler", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer" and "twig" services.

I can't imagine there is no way to get the full list of roles somehow. The documentation (unless I'm missing it), doesn't seem to do much to address this. Should I be injecting some "larger" service locator from somewhere?

1

There are 1 best solutions below

0
Ravioli87 On

https://symfony.com/doc/current/controller.html#accessing-configuration-values

$this->getParameter('security.role_hierarchy.roles');