Django 6.1.3

11.3 Sessions, auth, and the admin

Authentication backends and hash upgrades

How does authenticate walk AUTHENTICATION_BACKENDS, why does django.contrib.auth.hashers.check_password run a dummy hash for nonexistent usernames, and how does Django upgrade password hashes silently on login?

Logging a user in splits cleanly into two steps: authenticate verifies credentials and returns a User annotated with "user.backend", and login persists that user into the session. Separating authentication from session persistence lets a single Django project support username/password login, SSO tokens, and API keys through pluggable AUTHENTICATION_BACKENDS — while keeping password cryptography isolated inside django/contrib/auth/hashers.py.

How authenticate walks backends (and stops on PermissionDenied)

Open authenticate:

  1. Signature filtering via _get_compatible_backends: Before calling a backend, Django inspects signature(backend.authenticate) and tests "bind(request, **credentials)". If a custom token backend only accepts (request, token=...) and you pass username= / password=, Django skips it cleanly instead of crashing with TypeError.
  2. First match wins — unless PermissionDenied aborts the loop: Django tries each compatible backend in "settings.AUTHENTICATION_BACKENDS" order. Returning None passes control to the next backend; returning a user sets "user.backend = backend_path" (so login knows which backend to store in "BACKEND_SESSION_KEY") and returns immediately. Raising PermissionDenied breaks out of the entire loop immediately, letting a lockout or deny-list backend veto login before any fallback backend runs!
  3. Failure auditing with credential scrubbing: If no backend authenticates the request, Django fires user_login_failed after passing "credentials" through _clean_credentials so keys matching "api|token|key|secret|password|signature" are masked as "********************".

Timing-attack mitigation, harden_runtime, and transparent hash upgrades

Now open ModelBackend.authenticate — Django’s default database authentication backend. It fetches the user via get_by_natural_key(username) and passes (user, password) to check_password_with_timing_attack_mitigation, followed by ModelBackend.user_can_authenticate (which rejects is_active=False accounts).

Why does Django wrap password checking in a dedicated timing-attack helper? Because PBKDF2PasswordHasher in Django 6.1 defaults to 1,500,000 PBKDF2-HMAC-SHA256 iterations — nearly half a second of CPU time per login check! If ModelBackend.authenticate returned immediately in 1 ms when a username did not exist in "auth_user", an attacker could enumerate every valid username or email address on your site simply by measuring response times!

Django closes three distinct timing side channels across check_password_with_timing_attack_mitigation and verify_password:

  1. Nonexistent username (user is None): check_password_with_timing_attack_mitigation runs get_user_model()().set_password(password), executing the default 1,500,000-iteration PBKDF2 hasher once and discarding the result before returning None.
  2. Unusable or unrecognized password hash ("!" prefix from set_unusable_password()): verify_password calls make_password(...) with a random 40-character string so SSO-only or locked accounts take the exact same time as password accounts.
  3. Legacy lower-iteration hash on a wrong password: Suppose an old account still carries a 100,000-iteration PBKDF2 hash from an earlier Django release. Checking a wrong password takes only ~32 ms instead of ~488 ms — leaking that the account exists and has not logged in recently! When "not is_correct and not hasher_changed and must_update", verify_password calls BasePasswordHasher.harden_runtime, which on PBKDF2PasswordHasher runs the remaining 1,500,000 - 100,000 = 1,400,000 iterations to equalize runtime!

And when the password is correct on that legacy 100,000-iteration account (or an older algorithm listed further down "PASSWORD_HASHERS" like PBKDF2SHA1PasswordHasher while PBKDF2PasswordHasher or Argon2PasswordHasher sits at index 0)? AbstractBaseUser.check_password passes a "setter" callback into check_password: when is_correct and must_update, Django immediately re-encodes the verified plaintext password with the preferred PASSWORD_HASHERS[0] hasher and calls "self.save(update_fields=['password'])" — silently upgrading every active user’s password hash on login with zero password resets! (Notice it clears "self._password = None" first so hash upgrades are not mistaken for user-initiated password changes.)

Figure 11.2 Every latency bar and iteration count is parsed directly from ch11-auth and ch11-bench. Look at those four bars: valid login, wrong password, nonexistent username, and a legacy 100,000-iteration hash all finish within 3.5 ms (0.7%) of each other at ~487 ms!

Watch the live 100,000 -> 1,500,000 transparent PBKDF2 upgrade on "desk/"'s reporter account "ada", the PermissionDenied backend short-circuit, and the exact benchmark table:

Recorded on Django 6.1.3 ch11-auth script
3. Backends, PermissionDenied short-circuit, and PBKDF2 upgrade
  django_6_1_default: algorithm='pbkdf2_sha256' iterations=1,500,000
  transparent_rehash: authed=True backend='django.contrib.auth.backends.ModelBackend' iterations_before=100,000 iterations_after=1,500,000
  permission_denied_short_circuit: result=None backends_called=['deny_backend']
Recorded on Django 6.1.3 ch11-bench script
1. authenticate() timing-attack mitigation (1,500,000 PBKDF2 iters, 5 trials, ms)
  auth_path                                     median_ms      rel
  real user · valid password (1.5M)                 488.6    1.00x
  real user · wrong password (1.5M)                 486.0    0.99x
  nonexistent user · dummy hash (1.5M)              485.1    0.99x
  legacy 100k hash · wrong + harden_runtime         487.6    1.00x

Notice the practical consequence for test suites too: "desk/"'s production 1,500,000 PBKDF2 iterations cost ~488 ms per password check by design (making offline brute-forcing expensive), which is why Django’s test documentation recommends overriding "PASSWORD_HASHERS" with MD5PasswordHasher strictly inside test settings so creating or logging in 200 test users does not burn 100 seconds of CPU!

Authentication proves who the user is. Next we trace authorization — how PermissionsMixin evaluates "has_perm", why granting a permission mid-request is invisible to the same User instance, and how ContentTypeManager caches model metadata process-wide in Permission checks, groups, and ContentType caching.