Generate CSRF Token from frontend

Hi, what I am going to ask is a bit unconventional, but:
According to that part of the Django CSRF documentation, it is ok to post an arbitrary CSRF token pair

Does that mean, as I expect, that it is safe to generate and use a random CSRF token (through a reimplementation of how it is generated from Django) from a browser SPA before each request?

I already have a working PoC, I’m hesitating to clean and publish it as a standalone lib, but I don’t want to do it if:

  • this is actually insecure
  • this could break without notice from any Django update as the methods responsible for token generation are supposed to be used internally (it would be ok to me if that was at least considered a breaking change and I would be sure it would end-up in the changelog, but I don’t think that would be the case, as the frontend isn’t supposed to know the nature of the CSRF Token it handles)

Thanks in advance

As long as you can generate cryptographically strong token on frontend it should be fine.

Digging into sources:
Django documentation - Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?
The FAQ you refer to seems to confirm that

There is a good post on SO also:
Stack Overflow Django CSRF

Which points to Google Groups discussion where Django security team member explains the details and reasoning behind the implementation. I recommend the full read of it.

Exactly, my link was directly pointing to that specific subsection

That’s why it also seemed secure to me to generate it frontend-side, but you never know… I’d rather ask anyway, thanks for your answer

My only fear now is that the way Django generates and consumes those tokens could change in a higher version (what ends-up being stored in the cookies is not just a random string)
I’ll probably just add a way to automatically check that if I end-up releasing that lib, thank you