I'd like to check a method with access control, e.g. a method is only granted with a specific role. Therefore, I know two ways in Symfony:
- @Security annotation above the method (SensioFrameworkExtraBundle) OR
- Calling authorization_checker explizit within my method
When it comes to unit tests (for my case phpspec, but I think phpunit behaviour is the almost the same in that case), I would like to test that only anonymous users should be able to call a method. With number 2. , it's working fine. Here my setup:
RegistrationHandlerSpec:
class RegistrationHandlerSpec extends ObjectBehavior
{
function let(Container $container, AuthorizationCheckerInterface $auth) {
$container->get('security.authorization_checker')->willReturn($auth);
$this->setContainer($container);
}
function it_should_block_authenticated_users(AuthorizationCheckerInterface $auth)
{
$auth->isGranted("ROLE_USER")->willReturn(true);
$this->shouldThrow('Symfony\Component\Security\Core\Exception\AccessDeniedException')->during('process', array());
}
}
And within the RegistrationHandler, I have the following method:
class RegistrationHandler
{
public function process()
{
$authorizationChecker = $this->get('security.authorization_checker');
if ($authorizationChecker->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
// ...
}
}
Well, this approach is working fine - BUT normally, I would prefer using 1. with Security annotation (Sensio FrameworkExtraBundle), and therefore, it's not working / I don't know why no Exception gets triggered when it's written as an annotation:
/**
* @Security("!has_role('ROLE_USER')")
*/
public function process()
{
// ...
}
Does anyone know how to get this example to work by using the first approach with @Security annotation, which is way more readable and best practice recommended of symfony?