How to handle CSRF protection in Symfony forms?

To handle CSRF protection in Symfony forms, you can use the built-in CSRF protection feature provided by Symfony. Here is a step-by-step guide on how to implement CSRF protection in Symfony forms:

  1. Enable CSRF protection in the form type: In your form type class, you can enable CSRF protection by adding the following code in the configureOptions() method:
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; class YourFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // Add form fields here } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'csrf_protection' => true, ]); } }
  1. Render the CSRF token in the form template: In your form template file, you need to render the CSRF token by adding the following code:
{{ form_widget(form._token) }}
  1. Validate the CSRF token in the form submission: When processing the form submission in your controller, you need to validate the CSRF token to prevent CSRF attacks. You can do this by using the handleRequest() method of the form object:
public function yourAction(Request $request) { $form = $this->createForm(YourFormType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Process the form submission } // Render the form template }

By following these steps, you can easily implement CSRF protection in Symfony forms to secure your application against CSRF attacks.