Search code examples
javascriptdjangocsrfdjango-csrfcsrf-protection

Generate fresh django CSRF token on each login


I want my websites login form to have a new CSRF token generated everytime the page is refreshed.

I tried calling

logout(request)
request.session.flush()

But the hidden form field always has the same token, even after server restart.

This obviously means that django is reading the data from the cookie. How do I make it such that it ignores the cookies and generates a fresh one?

Alternatively is there a way for me to have an intermediate page that clears all cookies before going to the actual login page? How does one delete all cookies for my domain in Javascript?


Solution

  • You can manually reset the token as follows:

    from django.middleware.csrf import _get_new_csrf_key
    
    request.META["CSRF_COOKIE_USED"] = True
    request.META["CSRF_COOKIE"] = _get_new_csrf_key()
    

    In Django >= 1.6, you should instead use django.middleware.csrf.rotate_token(request), which does exactly this.