Skip to content

Commit

Permalink
csrf_token_lazy form option
Browse files Browse the repository at this point in the history
  • Loading branch information
tugrul committed Apr 23, 2024
1 parent 02c1e3c commit a1785e1
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 3 deletions.
Expand Up @@ -68,7 +68,7 @@ public function finishView(FormView $view, FormInterface $form, array $options):
if ($options['csrf_protection'] && !$view->parent && $options['compound']) {
$factory = $form->getConfig()->getFormFactory();
$tokenId = $options['csrf_token_id'] ?: ($form->getName() ?: $form->getConfig()->getType()->getInnerType()::class);
$data = (string) $options['csrf_token_manager']->getToken($tokenId);
$data = $options['csrf_token_lazy'] ? '' : (string) $options['csrf_token_manager']->getToken($tokenId);

$csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [
'block_prefix' => 'csrf_token',
Expand All @@ -87,6 +87,7 @@ public function configureOptions(OptionsResolver $resolver): void
'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.',
'csrf_token_manager' => $this->defaultTokenManager,
'csrf_token_id' => null,
'csrf_token_lazy' => false,
]);
}

Expand Down
Expand Up @@ -122,6 +122,26 @@ public function testGenerateCsrfToken()
$this->assertEquals('token', $view['csrf']->vars['value']);
}

public function testGenerateLazyCsrfToken()
{
$this->tokenManager->expects($this->once())
->method('getToken')
->with('TOKEN_ID')
->willReturn(new CsrfToken('TOKEN_ID', 'token'));

$view = $this->factory
->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'csrf_field_name' => 'csrf',
'csrf_token_manager' => $this->tokenManager,
'csrf_token_id' => 'TOKEN_ID',
'csrf_token_lazy' => true,
'compound' => true,
])
->createView();

$this->assertEquals('token', '');
}

public function testGenerateCsrfTokenUsesFormNameAsIntentionByDefault()
{
$this->tokenManager->expects($this->once())
Expand Down
Expand Up @@ -76,6 +76,7 @@
"csrf_message",
"csrf_protection",
"csrf_token_id",
"csrf_token_lazy",
"csrf_token_manager"
]
},
Expand Down
Expand Up @@ -11,8 +11,8 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice")
choice_loader data_class allow_file_upload csrf_message
choice_name empty_data attr csrf_protection
choice_translation_domain error_bubbling attr_translation_parameters csrf_token_id
choice_translation_parameters invalid_message auto_initialize csrf_token_manager
choice_value trim block_name
choice_translation_parameters invalid_message auto_initialize csrf_token_lazy
choice_value trim block_name csrf_token_manager
choices block_prefix
duplicate_preferred_choices by_reference
expanded data
Expand Down

0 comments on commit a1785e1

Please sign in to comment.