11.3 Sessions, auth, and the admin
Authentication backends and hash upgrades
How does authenticate walk AUTHENTICATION_BACKENDS, why does django 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/.
How authenticate walks backends (and stops on PermissionDenied)
Open authenticate:
- Signature filtering via
_get_compatible_backends: Before calling a backend, Django inspectssignature(backendand tests.authenticate) "bind(request, **credentials)". If a custom token backend only accepts(request, token=...)and you passusername=/password=, Django skips it cleanly instead of crashing withTypeError. - First match wins — unless
PermissionDeniedaborts the loop: Django tries each compatible backend in"settingsorder. Returning.AUTHENTICATION_BACKENDS" Nonepasses control to the next backend; returning a user sets"user(so.backend = backend_path" loginknows which backend to store in"BACKEND_SESSION_KEY") and returns immediately. RaisingPermissionDeniedbreaks out of the entire loop immediately, letting a lockout or deny-list backend veto login before any fallback backend runs! - Failure auditing with credential scrubbing: If no backend authenticates the request, Django fires
user_login_failedafter passing"credentials"through_clean_credentialsso keys matching"api|token|key|secret|password|signature"are masked as"********************".
Timing-attack mitigation, harden_runtime, and transparent hash upgrades
Now open ModelBackend — 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 (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 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:
- Nonexistent username (
user is None):check_password_with_timing_attack_mitigationrunsget_user_model()().set_password(password), executing the default1,500,000-iteration PBKDF2 hasher once and discarding the result before returningNone. - Unusable or unrecognized password hash (
"!"prefix fromset_unusable_password()):verify_passwordcallsmake_password(...)with a random 40-character string so SSO-only or locked accounts take the exact same time as password accounts. - 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 msinstead 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_passwordcallsBasePasswordHasher, which on.harden_runtime PBKDF2PasswordHasherruns the remaining1,500,000 - 100,000 = 1,400,000iterations 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 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 — silently upgrading every active user’s password hash on login with zero password resets! (Notice it clears "self first so hash upgrades are not mistaken for user-initiated password changes.)
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:
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']
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.