RegisterCsrfFeaturesPass.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Bundle\SecurityBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. use Symfony\Component\Security\Http\EventListener\CsrfProtectionListener;
  15. use Symfony\Component\Security\Http\EventListener\CsrfTokenClearingLogoutListener;
  16. /**
  17. * @author Christian Flothmann <christian.flothmann@sensiolabs.de>
  18. * @author Wouter de Jong <wouter@wouterj.nl>
  19. *
  20. * @internal
  21. */
  22. class RegisterCsrfFeaturesPass implements CompilerPassInterface
  23. {
  24. public function process(ContainerBuilder $container)
  25. {
  26. $this->registerCsrfProtectionListener($container);
  27. $this->registerLogoutHandler($container);
  28. }
  29. private function registerCsrfProtectionListener(ContainerBuilder $container)
  30. {
  31. if (!$container->has('security.authenticator.manager') || !$container->has('security.csrf.token_manager')) {
  32. return;
  33. }
  34. $container->register('security.listener.csrf_protection', CsrfProtectionListener::class)
  35. ->addArgument(new Reference('security.csrf.token_manager'))
  36. ->addTag('kernel.event_subscriber')
  37. ->setPublic(false);
  38. }
  39. protected function registerLogoutHandler(ContainerBuilder $container)
  40. {
  41. if (!$container->has('security.logout_listener') || !$container->has('security.csrf.token_storage')) {
  42. return;
  43. }
  44. $csrfTokenStorage = $container->findDefinition('security.csrf.token_storage');
  45. $csrfTokenStorageClass = $container->getParameterBag()->resolveValue($csrfTokenStorage->getClass());
  46. if (!is_subclass_of($csrfTokenStorageClass, 'Symfony\Component\Security\Csrf\TokenStorage\ClearableTokenStorageInterface')) {
  47. return;
  48. }
  49. $container->register('security.logout.listener.csrf_token_clearing', CsrfTokenClearingLogoutListener::class)
  50. ->addArgument(new Reference('security.csrf.token_storage'))
  51. ->addTag('kernel.event_subscriber')
  52. ->setPublic(false);
  53. }
  54. }