Symfony:检查事件监听器内的用户授权

时间:2017-05-12 22:07:23

标签: symfony

我是Symfony的新手(目前正在使用Symfony 3.2),我正在学习如何创建事件监听器,以便在每个控制器之前运行我的随机函数。我的目标是通过isGranted()函数检查用户是否已记录。看看我的代码

services.yml

> parameters:
> #    parameter_name: value
> 
> services:
>     app.form_login_authenticator:
>         class: AppBundle\Security\FormLoginAuthenticator
>         arguments: ["@router", "@security.password_encoder"]
>     app.init.action_listener:
>         class: AppBundle\EventListener\InitListener
>         tags:
>             - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

InitListener

> <?php namespace AppBundle\EventListener;
> 
> use AppBundle\Controller\InitController; use
> Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use
> Symfony\Component\HttpKernel\Event\FilterControllerEvent; use
> Symfony\Component\HttpFoundation\Session\Session; 
>
>  class InitListener {
>     
>     public function onKernelController(FilterControllerEvent $event)
>     {
>         $controller = $event->getController(); 
> 
>        
> 
>         //if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY'))
>         //{
>         // do somehting
>         //}else{
>         // do somehting
>         //}
>         if ($controller[0] instanceof InitController) {
>           
>         }
>         if (!is_array($controller)) {
>             return;
>         }
>    
>    
>     }
>  }

我应该怎么做才能在我的InitListener中使用isGranted()函数?

1 个答案:

答案 0 :(得分:4)

显然你应该将security.authorization_checker传递给你的听众。

首先在配置

 app.init.action_listener:
     class: AppBundle\EventListener\InitListener
     arguments: ["@security.authorization_checker"]
     tags:
         - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

然后在代码中

 <?php namespace AppBundle\EventListener;

 use AppBundle\Controller\InitController; 
 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; 
 use Symfony\Component\HttpKernel\Event\FilterControllerEvent; 
 use Symfony\Component\HttpFoundation\Session\Session; 
 use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface

 class InitListener {

     protected $authorizationChecker;

     public function __construct(AuthorizationCheckerInterface $authorizationChecker)
     {
         $this->authorizationChecker = $authorizationChecker;
     }

     public function onKernelController(FilterControllerEvent $event)
     {
         $controller = $event->getController(); 

         if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
             // DO YOUR STUFF
         }       

         if ($controller[0] instanceof InitController) {

         }
         if (!is_array($controller)) {
             return;
         }


     }
  }