feat: access denied handler

This commit is contained in:
Björn Fromme
2025-04-24 20:58:16 +02:00
parent 0e49a5cf99
commit b6ac9fb362
@@ -0,0 +1,55 @@
<?php
namespace App\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException', priority: 2)]
class AccessDeniedListener
{
public function __construct(
private readonly Security $security,
private readonly LoggerInterface $logger,
) {
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (false === $exception instanceof AccessDeniedException) {
return;
}
$request = $event->getRequest();
$route = $request->attributes->get('_route');
// Treat OAuth2 routes differently
if (in_array($route, ['oauth2_authorize', 'oauth2_token'])) {
$request->getSession()->getFlashBag()->add('info', 'Bitte melde dich an.');
$this->logger->info('OAuth2 authorization request', [
'uri' => $request->getRequestUri(),
]);
return;
}
if (null === $this->security->getUser()) {
$request->getSession()->getFlashBag()->add('info', 'Bitte melde dich an.');
} else {
$request->getSession()->getFlashBag()->add('error', 'Zugriff verweigert');
// Unset potentially set target path to avoid access denied errors
$request->getSession()->remove('_security.main.target_path');
}
$this->logger->warning('Access denied', [
'uri' => $request->getRequestUri(),
]);
}
}