7

I have a public Django site which uses CSRF protection.

I have not set the CSRF_COOKIE_DOMAIN. My site uses subdomains.

Sometimes, a user ends up having a csrftoken cookie set on .toplevel.com as well as on sub.toplevel.com. This causes problems, as CSRF checking fails if the wrong cookie is used in the check.

I would like to set a CSRF_COOKIE_DOMAIN to .toplevel.com. However, I would also like to delete any csrftoken cookies for any *.toplevel.com subdomains. How would I do this?

If I do not delete the other cookies, I will just end up in the original situation of having two cookies with the same name on different domains, which causes issues.

Krystian Cybulski
  • 10,789
  • 12
  • 67
  • 98

1 Answers1

12

I had a similar problem. The way I dealt with it is together with CSRF_COOKIE_DOMAIN I also changed the CSRF_COOKIE_NAME, making old "csrftoken" cookies obsolete.

lehins
  • 9,642
  • 2
  • 35
  • 49
  • the only downside is that it's not a very graceful approach (POST requests that come right after this new configuration will fail). – Tommaso Barbugli Nov 22 '14 at 21:11
  • 3
    It's very true, if this change is made in between someone doing a GET and then an immediate POST request, it will fail. It is a very unlikely case if there are not many users on site, but if does presents a big problem (if there are thousands of concurrent users for instance), it can be dealt with by temporarily overriding `django.middleware.csrf.CsrfViewMiddleware` and checking for both cookie names in `process_view` method. – lehins Nov 22 '14 at 21:28
  • @AlexeyKuleshevich can you help me with my problem too? http://stackoverflow.com/q/29559000/4029893. Seems like you would understand. – bad_keypoints Apr 10 '15 at 11:48