Symfony4使用kernel.exception重定向所有不具有管理员角色的用户

时间:2019-04-22 17:14:38

标签: php exception symfony4

我想使用kernel.exception将所有不具有管理员角色的用户重定向到主页

这是我的控制器页面:

<?php

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class ProduitController extends AbstractController
{
    /**
     * @Route("/produit", name="produit")
     * @IsGranted("ROLE_ADMIN")
     */
    public function index()
    {
        return $this->render('produit/index.html.twig');
    }
}

这是EventListener:

<?php

namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class NotAuthenticationListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if (!$exception instanceof AccessDeniedException) {
            return;
        }
        return new Response("Access Denied !");
    }
}

service.yaml

App\EventListener\NotAuthenticationListener:
    tags:
        - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
  

但是它不起作用   enter image description here

1 个答案:

答案 0 :(得分:0)

我总是 love 引用文档。在这种情况下,GetResponseForExceptionEvent

 /**
 * Allows to create a response for a thrown exception.
 *
 * Call setResponse() to set the response that will be returned for the
 * current request. The propagation of this event is stopped as soon as a
 * response is set.
 *
 * You can also call setException() to replace the thrown exception. This
 * exception will be thrown if no response is set during processing of this
 * event.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */

从本质上讲:在EventListener中返回某些内容只是……无用的。您必须在事件中致电setResponse并以这种方式设置您的回复。

希望有帮助; o)