【发布时间】:2019-04-22 17:14:37
【问题描述】:
我想用 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');
}
}
这是事件监听器:
<?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
【问题讨论】: