Skip to content

Fix CSRF verification failure when trying to log in using an old CSRF token

Sivert Olstad requested to merge fix-csrf-verification-login-issue into main

Closes #207 (closed). This PR fixes the issue with a custom CSRF failure view that redirects the user to the expected URL if the user is trying to log in and is already authenticated. If not, the default CSRF failure view is used.

A more in-depth explanation of the issue is provided in the view's docstring, also provided here:

Redirect to the expected URL if the user is trying to log in, but has already done so. If not, use the default CSRF failure view.

The redirect circumvents an issue where the user is presented with a "403 Forbidden CSRF verification failed" error when trying to log in in a browser tab loaded before logging in in another tab. Since the user is already authenticated in this case, it should be safe to redirect to the URL the user expects to see. All other CSRF failures are met with the default CSRF failure view.

The redirect does not check the provided credentials. This means that the user is redirected no matter what they input in the login form. This should be fine, since the user is already authenticated and no-one has more than one account.

The issue is mentioned in the Django documentation here: https://docs.djangoproject.com/en/5.0/ref/csrf/#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in

Merge request reports