【问题标题】:Symfony4 redirecting all users who not have admin role using kernel.exceptionSymfony4 使用 kernel.exception 重定向所有没有管理员角色的用户
【发布时间】: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

【问题讨论】:

    标签: php exception symfony4


    【解决方案1】:

    我总是喜欢引用文档。在这种情况下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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-17
      • 2020-02-16
      • 2018-07-02
      • 2017-11-19
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多