5

We've enabled CSRF Protection on a site.

When we do, it sometimes works, but most of the time it gets tripped and triggers false positives and doesn't allow our forms to be submitted.

Things we've observed:

  1. Some forms work, others don't
  2. Sometimes a browser doesn't place the CSRF cookie
  3. Sometimes two different browsers will have the same CSRF cookie
  4. Sometimes if I delete the CSRF Cookie and then refresh the browser, the cookie won't return
  5. Clearing the Craft cache seems to get forms working again in one browser but not another

Why are we seeing this weird behavior? What is happening?!

8

We got this sorted before I finished my Stack Exchange question so I figured I'd share if anyone else runs into similar behavior.

After some troubleshooting, we learned that the issue here was that some of our Forms were being cached by Craft's {% cache %} tag and others were not.

CSRF Cookies are unique per user per session, so you don't want to cache them.

In our situation, it wasn't obvious at first that a {% cache %} tag was wrapped around the form, because the {% cache %} tag was actually in a {% block %} in a parent layout file that was being extended.

While searching through the templates helped us track down part of the issue, we also found it helpful to look at what was being cached in the craft_templatecaches table. In the body column you can see what part of your template code is being cached, and we could see that the form, even though it didn't have {% cache %} tags around it in the template it was in, was being cached within a larger block of code.

Probably not the most mindblowing thing you will ever read, but it came in handy for me one long hour of one short day in history.

| improve this answer | |
  • 2
    Moral of the story... don't cache your CSRF tokens. :) – Brad Bell Nov 1 '14 at 2:49
  • Sounds like it had the potential of being a very painful issue to track down - glad you found it as soon as you did :) – Andris Sevcenko Nov 2 '14 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.