Leah Sapan
Leah Sapan

Reputation: 3791

Django site suddenly requiring users to clear their cookies to get a CSRF token

I run a Django site that hasn't undergone any updates in the last few months, yet all of a sudden I'm receiving a bunch of emails from users saying they're getting the following error:

CSRF Failed: CSRF cookie not set.

The bizarre thing is that refreshing the page does not fix the issue. The only way to resolve it is to have them manually clear their browser's cookies.

Bear in mind that they are still logged in after refreshing. So even though they aren't getting a CSRF cookie, Django is acknowledging their session.

While I'm glad they can clear their cookies to fix it, it's concerning to me as I can't fathom what is happening. It started happening around the same time that iOS 14.5 came out, so I initially thought it may somehow be related to that, but I just received a report from an Android user.

Has anyone run into this before? Is there any way to resolve this without putting a banner on the site explaining to clear cookies if you see the error?

Thanks!

Upvotes: 3

Views: 1068

Answers (1)

Leah Sapan
Leah Sapan

Reputation: 3791

Thanks for your comments and suggestions! I ended up figuring out what was going on.

So for some reason, Django won't create a new CSRF cookie (even if it has been expired/deleted) if the session cookie is still valid. This seems like a bug, but maybe there's a security reason for it.

In my case, I had extended SESSION_COOKIE_AGE to 60 * 60 * 24 * 365 * 10, or 10 years. It turns out the default value for CSRF_COOKIE_AGE is 1 year. As such, everyone that had been logged in for a year no longer had a valid CSRF cookie, and Django wouldn't issue them a new one because their session was still valid for another 9 years.

Upvotes: 3

Related Questions