Search code examples
djangocookiesdjango-csrfdjango-4.0

Increase Django CSRF tocken longevity


I get lots of Django CSRF errors due to timeout.

In normal operations, the form submissions are OK. But, if I leave the page for a few hours and then submit it, it will fails with the

Forbidden (403)
CSRF verification failed. Request aborted

screen. To overcome this issue, I added the following line to the settings.py :

SESSION_COOKIE_AGE = 604800 # one week

But a few hours leading to timeout means that this line has had no effect. I need CSRF tokens longevity be increased to a few days rather than minutes.

How to achieve this?

Django CSRF


Solution

  • Theory

    CSRF_COOKIE_AGE¶ Default: 31449600 (approximately 1 year, in seconds)

    The age of CSRF cookies, in seconds.

    The reason for setting a long-lived expiration time is to avoid problems in the case of a user closing a browser or bookmarking a page and then loading that page from a browser cache. Without persistent cookies, the form submission would fail in this case.

    Some browsers (specifically Internet Explorer) can disallow the use of persistent cookies or can have the indexes to the cookie jar corrupted on disk, thereby causing CSRF protection checks to (sometimes intermittently) fail. Change this setting to None to use session-based CSRF cookies, which keep the cookies in-memory instead of on persistent storage.

    To increase the longevity of CSRF tokens in Django, you need to modify the CSRF token cookie settings. By default, Django sets the CSRF token cookie to expire when the user's session ends. However, you can extend the expiration time by configuring the CSRF_COOKIE_AGE setting in your

    settings.py file.

    CSRF_COOKIE_AGE = 604800 # 1 week in seconds