Cross-Site Request Forgery (CSRF) is a dangerous web vulnerability that tricks authenticated users into performing unwanted actions on a web application. If you're building or managing Symfony-based applications, it's essential to know how CSRF works and how to mitigate it effectively.
In this post, we'll break down how CSRF affects Symfony apps, show multiple code examples, and guide you in using a Free Website Security Scanner to secure your web application.
CSRF occurs when a malicious website tricks a user’s browser into sending a request to a different website where the user is authenticated (such as submitting a form to transfer funds or change a password).
A victim is logged in to their Symfony admin panel. They visit a malicious website that secretly sends a POST request to https://example.com/admin/delete-user/1, resulting in an unauthorized deletion.
Symfony has built-in CSRF protection, especially for forms. But custom API endpoints and form misconfigurations can still leave room for exploitation.
Symfony’s Form component provides automatic CSRF protection. Here's how you can enable and verify it properly.
// src/Form/UserType.php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class)
->add('save', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'user_item',
]);
}
}
{{ form_start(form) }}
{{ form_row(form.username) }}
{{ form_row(form.save) }}
{{ form_end(form) }}
This is an example of a dangerous form vulnerable to CSRF if rendered manually without token protection:
<form method="POST" action="/user/delete/1">
<input type="submit" value="Delete User">
</form>
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
public function delete(Request $request, CsrfTokenManagerInterface $csrfTokenManager)
{
$submittedToken = $request->request->get('_token');
if ($csrfTokenManager->isTokenValid(new CsrfToken('delete-item', $submittedToken))) {
// Proceed with deletion
} else {
throw new \RuntimeException('Invalid CSRF token');
}
}
Use this method for routes not using Symfony's Form component, like API endpoints.
You can use our website vulnerability scanner to check for CSRF and other critical flaws.
📸 Screenshot of the free website security checker tool webpage
Screenshot of the free tools webpage where you can access security assessment tools.
After running a scan for a Website Security check, you will receive a detailed report that highlights if your site is vulnerable to CSRF or other issues like XSS, SQLi, etc.
📸 Screenshot of a vulnerability assessment report generated by the free tool
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Symfony APIs often use JWT or session-based tokens. Here's how to secure a custom API route manually:
// routes/api.php
/**
* @Route("/api/update-email", methods={"POST"})
*/
public function updateEmail(Request $request, CsrfTokenManagerInterface $csrfTokenManager)
{
$token = $request->headers->get('X-CSRF-TOKEN');
if (!$csrfTokenManager->isTokenValid(new CsrfToken('api-action', $token))) {
return new JsonResponse(['error' => 'Invalid CSRF token'], 403);
}
// Continue with update
}
Add the token in your JavaScript calls:
fetch('/api/update-email', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': 'your_token_here',
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: 'user@example.com' })
});
Want to learn more about securing web applications? Check out more tutorials and vulnerability breakdowns on our blog:
👉 Pentest Testing Corp
Symfony offers great built-in tools to prevent CSRF, but developers must configure and use them correctly. For every form or endpoint, always ensure that a CSRF token is validated.
Scan your site now at free.pentesttesting.com and secure your app before attackers exploit it.