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

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  19. *
  20. * @final
  21. */
  22. class CsrfProtectionListener implements EventSubscriberInterface
  23. {
  24. private $csrfTokenManager;
  25. public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
  26. {
  27. $this->csrfTokenManager = $csrfTokenManager;
  28. }
  29. public function checkPassport(CheckPassportEvent $event): void
  30. {
  31. $passport = $event->getPassport();
  32. if (!$passport->hasBadge(CsrfTokenBadge::class)) {
  33. return;
  34. }
  35. /** @var CsrfTokenBadge $badge */
  36. $badge = $passport->getBadge(CsrfTokenBadge::class);
  37. if ($badge->isResolved()) {
  38. return;
  39. }
  40. $csrfToken = new CsrfToken($badge->getCsrfTokenId(), $badge->getCsrfToken());
  41. if (false === $this->csrfTokenManager->isTokenValid($csrfToken)) {
  42. throw new InvalidCsrfTokenException('Invalid CSRF token.');
  43. }
  44. $badge->markResolved();
  45. }
  46. public static function getSubscribedEvents(): array
  47. {
  48. return [CheckPassportEvent::class => ['checkPassport', 512]];
  49. }
  50. }