symfony / ux

Symfony UX initiative: a JavaScript ecosystem for Symfony
https://ux.symfony.com/
MIT License
849 stars 312 forks source link

Lazy CSRF Token Component #412

Open alexander-schranz opened 2 years ago

alexander-schranz commented 2 years ago

In the SuluFormBundle we are lazy loading the CSRF Token via JavaScript. For this we need to manipulate the "exist" CSRF token generation by creating a "DisabledCsrfTokenManager":

https://github.com/sulu/SuluFormBundle/blob/4b52fdfb623e126e43b38fa0acfce3af5b0982a5/Csrf/DisabledCsrfTokenManager.php#L57-L59

This "Disabled" CSRFTokenManager never access the Session and so keep pages with a Symfony Forms cached.

The form is created with that "DisabledCsrfTokenManager": https://github.com/sulu/SuluFormBundle/blob/4b52fdfb623e126e43b38fa0acfce3af5b0982a5/Form/Builder.php#L225

And the JavaScript on the website then loads the real CSRF Token. Some docs here:

https://github.com/sulu/SuluFormBundle/blob/2.x/Resources/doc/csrf.md#ajax

The ajax request just get the CSRF token via the symfony core csrf token manager: https://github.com/sulu/SuluFormBundle/blob/4b52fdfb623e126e43b38fa0acfce3af5b0982a5/Controller/FormTokenController.php#L33

This way we can use CSRF Token protection on cached pages. I even did think that it would be great to create a JS component which loads the CSRF Token only when needed so e.g. if somebody begins to write something into the form or before submitting the form. That way additional request to application server would also be avoided and creating a session for it.

I know that CSRF Token protection has still its discussion points, but think its one of the only shipped spam protection with symfony and so widely used and have a symfony/ux component which allows to lazy load it would be a great feature.

tgalopin commented 2 years ago

I do the same in my personal apps : I think it would be a great component for Symfony UX! If you're open to create a PR, go for it IMO

carsonbot commented 6 months ago

Thank you for this issue. There has not been a lot of activity here for a while. Has this been resolved?

alexander-schranz commented 6 months ago

Please keep this open :)

carsonbot commented 1 week ago

Thank you for this issue. There has not been a lot of activity here for a while. Has this been resolved?