vendor/symfony/security-http/EventListener/CsrfProtectionListener.php line 36

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Security\Http\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  13. use Symfony\Component\Security\Csrf\CsrfToken;
  14. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  15. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  16. use Symfony\Component\Security\Http\Event\CheckPassportEvent;
  17. /**
  18.  * @author Wouter de Jong <wouter@wouterj.nl>
  19.  *
  20.  * @final
  21.  * @experimental in 5.1
  22.  */
  23. class CsrfProtectionListener implements EventSubscriberInterface
  24. {
  25.     private $csrfTokenManager;
  26.     public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
  27.     {
  28.         $this->csrfTokenManager $csrfTokenManager;
  29.     }
  30.     public function checkPassport(CheckPassportEvent $event): void
  31.     {
  32.         $passport $event->getPassport();
  33.         if (!$passport->hasBadge(CsrfTokenBadge::class)) {
  34.             return;
  35.         }
  36.         /** @var CsrfTokenBadge $badge */
  37.         $badge $passport->getBadge(CsrfTokenBadge::class);
  38.         if ($badge->isResolved()) {
  39.             return;
  40.         }
  41.         $csrfToken = new CsrfToken($badge->getCsrfTokenId(), $badge->getCsrfToken());
  42.         if (false === $this->csrfTokenManager->isTokenValid($csrfToken)) {
  43.             throw new InvalidCsrfTokenException('Invalid CSRF token.');
  44.         }
  45.         $badge->markResolved();
  46.     }
  47.     public static function getSubscribedEvents(): array
  48.     {
  49.         return [CheckPassportEvent::class => ['checkPassport'128]];
  50.     }
  51. }