Skip to content

Commit

Permalink
[Security] Implement stateless headers/cookies-based CSRF protection
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Oct 8, 2024
1 parent 0df8534 commit 6a49eed
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion Extension/Csrf/Type/FormTypeCsrfExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Util\ServerParams;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
Expand All @@ -35,6 +36,8 @@ public function __construct(
private ?TranslatorInterface $translator = null,
private ?string $translationDomain = null,
private ?ServerParams $serverParams = null,
private array $fieldAttr = [],
private ?string $defaultTokenId = null,
) {
}

Expand Down Expand Up @@ -73,6 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options):
$csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [
'block_prefix' => 'csrf_token',
'mapped' => false,
'attr' => $this->fieldAttr + ['autocomplete' => 'off'],
]);

$view->children[$options['csrf_field_name']] = $csrfForm->createView($view);
Expand All @@ -81,13 +85,24 @@ public function finishView(FormView $view, FormInterface $form, array $options):

public function configureOptions(OptionsResolver $resolver): void
{
if ($defaultTokenId = $this->defaultTokenId) {
$defaultTokenManager = $this->defaultTokenManager;
$defaultTokenId = static fn (Options $options) => $options['csrf_token_manager'] === $defaultTokenManager ? $defaultTokenId : null;
}

$resolver->setDefaults([
'csrf_protection' => $this->defaultEnabled,
'csrf_field_name' => $this->defaultFieldName,
'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.',
'csrf_token_manager' => $this->defaultTokenManager,
'csrf_token_id' => null,
'csrf_token_id' => $defaultTokenId,
]);

$resolver->setAllowedTypes('csrf_protection', 'bool');
$resolver->setAllowedTypes('csrf_field_name', 'string');
$resolver->setAllowedTypes('csrf_message', 'string');
$resolver->setAllowedTypes('csrf_token_manager', CsrfTokenManagerInterface::class);
$resolver->setAllowedTypes('csrf_token_id', ['null', 'string']);
}

public static function getExtendedTypes(): iterable
Expand Down

0 comments on commit 6a49eed

Please sign in to comment.