admin管理员组

文章数量:1432446

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?

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?

Share Improve this question asked Mar 16, 2015 at 16:25 rep_movsdrep_movsd 6,9054 gold badges35 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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.

Try to set the CSRF_COOKIE_AGE=None to use session-based CSRF cookies, which keep the cookies in-memory instead of on persistent storage. I guess the CSRF token should then change if you logout a user. See the docs.

本文标签: javascriptGenerate fresh django CSRF token on each loginStack Overflow