DEV Community

Cover image for Prevent CSRF Vulnerabilities in Symfony Easily
Pentest Testing Corp
Pentest Testing Corp

Posted on

1 2 1

Prevent CSRF Vulnerabilities in Symfony Easily

Cross-Site Request Forgery (CSRF) is one of the most common web application vulnerabilities, and yes β€” even popular PHP frameworks like Symfony are not immune.

In this blog post, we'll walk through:

  • What CSRF is
  • How CSRF attacks work in real-world Symfony applications
  • How to prevent CSRF in Symfony with actual code examples
  • How to use our Free Website Security Checker to scan your web apps
  • And how to review the results with a sample security report

Prevent CSRF Vulnerabilities in Symfony Easily

πŸ” This post is part of our ongoing series on secure web development at Pentest Testing Corp.


🧠 What is CSRF?

Cross-Site Request Forgery (CSRF) tricks a victim into submitting an unwanted request to a web application in which they are currently authenticated.

For example, imagine a banking app where clicking a crafted link can cause the user to unknowingly transfer money.


🎯 How CSRF Attacks Target Symfony Applications

Here’s an example of a vulnerable Symfony controller that changes a user's email without any CSRF protection:

// src/Controller/ProfileController.php
public function updateEmail(Request $request, UserRepository $userRepository): Response
{
    $user = $this->getUser();
    $newEmail = $request->request->get('email');

    $user->setEmail($newEmail);
    $userRepository->save($user);

    return new Response('Email updated successfully!');
}
Enter fullscreen mode Exit fullscreen mode

If this endpoint is hit via a POST request, even from a malicious source, Symfony will process it β€” unless CSRF protection is explicitly added.


🚨 Real-World CSRF Exploit Scenario

Let’s say the victim is logged into your Symfony app. An attacker sends them this HTML email:

<form action="https://target-site.com/profile/update-email" method="POST">
    <input type="hidden" name="email" value="attacker@example.com">
    <input type="submit">
</form>
<script>document.forms[0].submit();</script>
Enter fullscreen mode Exit fullscreen mode

If there's no CSRF token verification, the email change happens silently!


πŸ› οΈ Fixing CSRF in Symfony (with Examples)

Symfony provides CSRF protection via the Form component and CSRF Token Manager.

βœ… 1. Protecting with Form Type

When you use Symfony’s built-in forms, CSRF is automatically handled:

use Symfony\Component\Form\Extension\Core\Type\FormType;

$builder->add('email', EmailType::class)
        ->add('save', SubmitType::class);
Enter fullscreen mode Exit fullscreen mode

In your Twig template:

{{ form_start(form) }}
    {{ form_widget(form) }}
{{ form_end(form) }}
Enter fullscreen mode Exit fullscreen mode

This includes a hidden CSRF token field like:

<input type="hidden" name="_token" value="...">
Enter fullscreen mode Exit fullscreen mode

Symfony will validate it on submit.


βœ… 2. Manual CSRF Token Validation (e.g., for API or AJAX)

If you're not using Symfony Forms:

use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Csrf\CsrfToken;

public function updateEmail(Request $request, CsrfTokenManagerInterface $csrfTokenManager)
{
    $token = new CsrfToken('email_update', $request->request->get('_token'));

    if (!$csrfTokenManager->isTokenValid($token)) {
        throw new AccessDeniedHttpException('Invalid CSRF token.');
    }

    // Continue with email update...
}
Enter fullscreen mode Exit fullscreen mode

Generate token in Twig:

<input type="hidden" name="_token" value="{{ csrf_token('email_update') }}">
Enter fullscreen mode Exit fullscreen mode

πŸ–ΌοΈ Screenshot: Free Website Vulnerability Scanner Tool

Screenshot of the free tools webpage where you can access security assessment tools.Easily scan your website for CSRF and other common web vulnerabilities.

Use our tool for a Website Security check if your forms and routes are vulnerable to CSRF.


🧾 Screenshot: Vulnerability Assessment Report

An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.Sample CSRF vulnerability discovered in a Symfony route to check Website Vulnerability.

Our free scanner gives you detailed reporting on every detected vulnerability, including CSRF, with remediation guidance.


πŸ“ˆ Pro Tips for Preventing CSRF in Symfony

  • βœ… Always use CSRF tokens, even for simple forms.
  • βœ… Use Symfony Forms when possibleβ€”they handle CSRF automatically.
  • βœ… For API routes, validate CSRF tokens manually.
  • βœ… Use secure headers like SameSite=Strict in cookies to limit session exposure.

πŸ“š Further Reading & Resources


βœ… Conclusion

CSRF is easy to overlook, but even easier to fix β€” especially when using Symfony properly. Whether you're working with forms, APIs, or admin dashboards, always validate CSRF tokens.

Want to know if your Symfony project is vulnerable?

πŸ‘‰ Try our Free Website Security Checker at https://free.pentesttesting.com/

It takes just a few seconds and gives you a full vulnerability report, including CSRF risks!

Top comments (0)