feat: improved handling and logging of access denied errors

This commit is contained in:
Björn Fromme
2025-04-28 11:10:35 +02:00
parent aa708e491c
commit c37309b3c1
3 changed files with 29 additions and 12 deletions
+12 -6
View File
@@ -4,20 +4,26 @@ namespace App\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
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
class AccessDeniedListener implements EventSubscriberInterface
{
public function __construct(
private readonly Security $security,
private readonly LoggerInterface $logger,
private readonly LoggerInterface $authLogger,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => ['onKernelException', 2],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
@@ -33,7 +39,7 @@ class AccessDeniedListener
if (in_array($route, ['oauth2_authorize', 'oauth2_token'])) {
$request->getSession()->getFlashBag()->add('info', 'Bitte melde dich an.');
$this->logger->info('OAuth2 authorization request', [
$this->authLogger->info('OAuth2 authorization request', [
'uri' => $request->getRequestUri(),
]);
@@ -48,7 +54,7 @@ class AccessDeniedListener
$request->getSession()->remove('_security.main.target_path');
}
$this->logger->warning('Access denied', [
$this->authLogger->warning('Access denied', [
'uri' => $request->getRequestUri(),
]);
}
+2 -2
View File
@@ -33,7 +33,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
private readonly ApiClient $apiClient,
private readonly EntityManagerInterface $entityManager,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger,
private readonly LoggerInterface $authLogger,
) {
}
@@ -106,7 +106,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$this->logger->info('Login', [
$this->authLogger->info('Login', [
'email' => $token->getUserIdentifier(),
]);