作者:刘浩不来丷上海594865126 | 来源:互联网 | 2023-05-19 11:27
Idliketocheckamethodwithaccesscontrol,e.g.amethodisonlygrantedwithaspecificrole.
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:
我想检查一个带访问控制的方法,例如:方法仅授予特定角色。因此,我在Symfony中了解两种方式:
- @Security annotation above the method (SensioFrameworkExtraBundle) OR
- 方法上方的@Security注释(SensioFrameworkExtraBundle)或
- Calling authorization_checker explizit within my method
- 在我的方法中调用authorization_checker exploizit
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:
当谈到单元测试时(对于我的案例phpspec,但我认为phpunit行为在这种情况下几乎相同),我想测试只有匿名用户应该能够调用方法。数字2,它工作正常。在这里我的设置:
RegistrationHandlerSpec:
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:
在RegistrationHandler中,我有以下方法:
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:
好吧,这种方法工作正常 - 但通常情况下,我更喜欢使用1.带有安全注释(Sensio FrameworkExtraBundle),因此,它不起作用/我不知道为什么没有在将它作为注释编写时触发异常:
/**
* @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?
有没有人知道如何通过使用@Security注释的第一种方法来使这个例子工作,这是更可读和symfony推荐的最佳实践?
1 个解决方案