Skip to content

Instantly share code, notes, and snippets.

@kriswallsmith
Created March 2, 2012 21:10
Show Gist options
  • Save kriswallsmith/1961437 to your computer and use it in GitHub Desktop.
Save kriswallsmith/1961437 to your computer and use it in GitHub Desktop.
<?php
namespace OpenSky\Bundle\MainBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\SecurityContextInterface;
/**
* Listens to kernel.request after the router and checks required role.
*/
class RouteSecurityListener
{
private $security;
public function __construct(SecurityContextInterface $security)
{
$this->security = $security;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$route = $request->attributes->get('_route');
$role = $request->attributes->get('_role');
if ($role && !$this->security->isGranted($role)) {
$message = $route
? sprintf('The "%s" route requires the "%s" role.', $route, $role)
: sprintf('This route requires the "%s" role.', $role);
throw new AccessDeniedException($message);
}
}
}
@jmikola
Copy link

jmikola commented Mar 2, 2012

This is preferable for fine-grain control over route security, since maintaining a set of patterns in the security config often meant we had to keep paths in multiple places in sync with each other. I think it'd also be great to allow role restrictions to be inherited when routes are imported, by allowing _role to be specified on the import. In the case of importing a routing file that defined /backend/products and related routes, we could require the product-editor role once.

@kriswallsmith
Copy link
Author

This is also much faster than looping over the access map in addition to looping over the routes. However it is limited to just checking roles, but that's all I need right now :)

@jmikola
Copy link

jmikola commented Mar 2, 2012

Indeed.

@schmittjoh
Copy link

Why are you not applying this to your action directly?

@kriswallsmith
Copy link
Author

We don't use any annotations on controllers, so applying this to actions directly would be a lot (more) of boilerplate code all over the place.

@jonathaningram
Copy link

It's probably a bit of a micro-optimisation, but you don't really need to retrieve the $route unless you enter that if.

@schmittjoh
Copy link

You can also use:

jms_security_extra:
    method_access_control:
        "AcmeFooBundle:Blog:edit": "hasRole('ROLE_EDITOR')"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment