Search code examples
symfonyauthorizationsymfony-routing

Custom authorization check before executing controller


I've added a new option roles in routing settings for checking permissions for menu items during a menu rendering.
It would be great if I could use the option for authorization check before executing corresponding controllers.

Example:

some_route:
    path: /path/
    defaults:   { _controller: MyBundle:Controller:action }
    option:
        roles: [ROLE_MANAGER, ROLE_ADMIN]

I need check if user has access to the controller based on his roles before executing controller itself.
How does it possible? Any ideas?

UPDATE
Why I need the roles option?
There are 4 different roles and many routes in the project. Some of routes are protected and visible only for users with specific roles.
For now all authorization checks are performed inside controllers by denyAccessUnlessGranted() method.
I also use KnpMenuBundle for building menu. And during the menu rendering I need check accessibility of each item for a current logged-in user. If the user has no access to an item it is excluded and the user doesn't see it.
In order to check if user has access to an item or not I added the option I've mentioned, where I define roles which have access to a route. And this roles options defines absolutely the same roles as in checks in denyAccessUnlessGranted(). And I think as I already have these role settings why don't use it for controller authorization checks and remove redundant code from them.


Solution

  • I know this is not much of an answer but you asked for it.

    Add a kernel.controller listener and check the permissions there.