Reputation: 61
We've been experiencing issues with duplicate CSRF token cookies in Django in our most recent release. We just upgraded from Django 1.4 to 1.6 and we never had any issues back in 1.4. Basically, everything starts fine for each user, but at some point they end up having more than one CSRF token cookie and the browser gets confused and doesn't know which one to use. It typically chooses wrong and causes CSRF failure issues. Our site uses multiple sub-domains, so there's typically a cookie for .site.com, .sub.site.com, site.com, and other variants.
We tried setting "CSRF_COOKIE_DOMAIN" to .site.com, and that seemed to make the issue happen less frequently, but it still happened occasionally when sub-domains were being used and users were logging out and logging back in as other users.
We also discovered that the favicon shortcut wasn't being defined in our base template, causing an extra request to go through the middleware, but that was fixed. We then confirmed that only the real request was going through the middleware and not any of the static or media files.
We still can't reproduce the issue on command, and typically whenever it does happen then clearing cookies works as a temporary fix, but it still keeps happening periodically. Does anyone know why this might be happening? Is there something that we're missing in the docs?
Thanks.
EDIT:
One thing I forgot to mention is that we have multiple server environments (site.com, demo.site.com, and beta.site.com). After a little more digging, it looked like users who were testing on beta and then used production had cross-environment cookie collisions. Just now we tried setting the csrf cookie domains for each environment to ".beta.site.com" and ".demo.site.com" instead of just ".site.com" and that seemed to help, especially when you clear your cookies between working in each environment. However, there's still potential for collisions between .site.com cookies on production colliding in beta and demo, but that's less of an issue at least.
So is there anything more we can do about this? Also, is there anything we can do once we push this to production when users have old "site.com" cookies that run into collisions with the new specified ".site.com" cookies?
EDIT 2:
I posted the solution, but it won't let me accept it for a few days.
Upvotes: 4
Views: 655
Reputation: 61
I think we finally figured it out. The separate "CSRF_COOKIE_DOMAIN" for each environment (".beta.site.com", ".demo.site.com", etc.) stopped the cross-environment issues. We also ended up setting "CSRF_COOKIE_NAME" to "csrf_token" instead of the default "csrftoken" so that users with old csrftoken cookies weren't negatively affected.
Upvotes: 1