yoda questions meme

How to add CSRF protection to Symfony 5+ forms

How CSRF works

What you are basically doing with CSRF is trying to make sure a hacker has not created a fake form to gather private information from your user.

You want your app to create a unique string and save it on the server in a session cookie or database, redis etc. Then you add that string to a form in a hidden field. When the form is submitted by the user you fetch the CSRF string you created server side and compare it to the value in the form.

If the values match there was no hacking attempt and you can trust it. If the values do not match then a hacker has probably done something and you should not trust the form submission.

My interweb searches on this subject were not very helpful the other day. So, today I dig into the docs.

on the case detective meme
Time to be a Symfony detective

The first place to look is in the documentation for the security component. That article doesn’t say much about CSRF, but it has lots of links to how the Security system works in Symfony.

In the article above is a link of gold, How to implement CSRF protection.  I didn’t even find this in my  searches for “Symfony CSRF” protection yesterday. I am not sure why, maybe it was further down the list. This article contains some very helpful information though.

You may want to check your current configuration to see if you have enabled CSRF.

So it appears here that just adding to the configuration adds CSRF protection to all forms? Which I find confusing. Like this is truly the only change we need to make?

no way meme
Is it really that easy?

But that is only with forms created using Symfony form tools. If you create a custom form, not using Symfony form system, say REACT, you will need to implement your own CSRF more here.

Here is a good video about Symfony form security and shows how to quickly build an entire app with Symfony


If you need to use PUT with CSRF protection see this SymfonyCast.

Here is a nice SymfonyCast about CSRF with a REST API.

SymfonyCast about CSRF with ReactJs.

Samesite cookie configuration in Symfony docs

Here is a nice Symfony bundle for 2 factor identification with CSRF

This awesome SymfonyCast covers security in  Symfony version 4 but most of it still applies to Symfony 5. It talks more about how using the Symfony form bundle automatically adds CSRF protection when enabled.







3 responses to “How to add CSRF protection to Symfony 5+ forms”

  1. […] How to add CSRF protection to Symfony 5+ formshttps://akashicseer.com/web-security/how-to-add-csrf-protection-to-symfony-5-forms/ […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.