Skip to content

Instantly share code, notes, and snippets.

@kriswallsmith
Created March 2, 2012 21:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
}
}
}
@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