【发布时间】:2016-06-05 10:16:56
【问题描述】:
我想检查一个带有访问控制的方法,例如一个方法只被授予一个特定的角色。因此,我在 Symfony 中知道两种方式:
- 方法上方的@Security注解(SensioFrameworkExtraBundle)或
- 在我的方法中调用 authorization_checker explizit
当涉及到单元测试时(对于我的情况是 phpspec,但我认为 phpunit 的行为在这种情况下几乎相同),我想测试只有匿名用户才能调用方法。使用数字 2. ,它工作正常。这是我的设置:
注册处理程序规范:
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());
}
}
在 RegistrationHandler 中,我有以下方法:
class RegistrationHandler
{
public function process()
{
$authorizationChecker = $this->get('security.authorization_checker');
if ($authorizationChecker->isGranted('ROLE_USER')) {
throw new AccessDeniedException();
}
// ...
}
}
好吧,这种方法运行良好 - 但通常情况下,我更喜欢使用 1. with Security annotation (Sensio FrameworkExtraBundle),因此,它不起作用/我不知道为什么在编写为注释:
/**
* @Security("!has_role('ROLE_USER')")
*/
public function process()
{
// ...
}
有谁知道如何通过使用带有@Security 注释的第一种方法来使这个示例工作,这种方法更易读,推荐symfony 的最佳实践?
【问题讨论】:
标签: phpunit acl symfony phpspec