How to add CSRF protection to custom forms in Symfony?

To add CSRF protection to custom forms in Symfony, you can follow these steps:

  1. Generate a CSRF token in your form builder:
use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Security\Csrf\CsrfTokenManager; // in your form builder $csrfTokenManager = $this->get('security.csrf.token_manager'); $csrfToken = $csrfTokenManager->getToken('customForm')->getValue(); $formBuilder->add('csrf_token', HiddenType::class, array( 'data' => $csrfToken, ));
  1. Validate the CSRF token in your form handling controller:
use Symfony\Component\Security\Csrf\CsrfToken; use Symfony\Component\Security\Csrf\CsrfTokenManager; // in your form handling controller $csrfTokenManager = $this->get('security.csrf.token_manager'); $csrfToken = new CsrfToken('customForm', $request->request->get('csrf_token')); if (!$csrfTokenManager->isTokenValid($csrfToken)) { throw new \RuntimeException('CSRF token is invalid.'); }

By following these steps, you can add CSRF protection to your custom forms in Symfony to prevent CSRF attacks.