CSRF validation failed when trying to login to an already registered Django app

Here's what I did:

  • I have two tabs open in my browser and I have a login form loaded in both tabs.

  • Log in with the required credentials on the first tab.

  • I try to login again by providing credentials in the second tab.
  • I get an error on the second tab: CSRF verification failed. Request aborted

    .

I have used {% csrf_token %}

in my login form and CsrfViewMiddleware

in settings.py

.

Also, I tried the same with the default admin and got the same error.

+3


source to share


1 answer


This is to be expected. The login operation rotates the CSRF token, otherwise the token could be used from outside the authenticated session.

Hence what happens in your case:

  • Get Tab 1 login page (with unauthorized "form" CSRF token)
  • Get Tab 2 login page (with unauthorized CSRF token "format")
  • Entering Tab 1, CSRF token "cookie" gets server-side round-robin, browser cookie is updated
  • Try to enter Tab 2, will send a new cookie (tabs don't split sessions) but old form token.
  • The second login request is rejected (because the "form" token and the cookie token mismatch).


This is an interaction between the fact that using multiple browser tabs does not separate sessions and the fact that the login operation loops through the CSRF cookie sent by the server.

Any page loaded prior to a login operation that takes place in the same session (for example, in a different browser tab) will now have the wrong CSRF token.

+3


source







All Articles