If CSRF-protection fails with Django CMS ...

2016-03-26 | #django, #solution, #webdev

.. make sure to check the cache settings of the plugin or app part the CSRF-token is rendered in. A cached CSRF-token will NOT work! Why is that? Lets have a look at how CSRF-tokens work in Django:

CSRF-tokens are managed by a default middleware in Django, which sets the token for use in templates. What this middleware also does is keeping this value in sync with the "csrfmiddlewaretoken"-cookie, which is needed for POST-requests, by setting this cookie in the request's response header.

The moment you cache anything containing a CSRF-token you circumvent the middleware, rendering the byte-result directly from storage. This way everybody gets the same token and additionally template and cookie token get out of sync. The result of this is, that logged in users as well as the first visitor after a cache refresh can use your form normally, while for everybody else it just won't work. Bummer!

So keep the following fact close to your heart: you can not cache plugins that contain individual data! But that's what the modular caching of Django CMS is there for.