11.2 Sessions, auth, and the admin
LazyObject, get_user, and session hash verification
Why does AuthenticationMiddleware attach a SimpleLazyObject instead of fetching the user immediately, and how does get_session_auth_hash invalidate old sessions after a password change?
Remember what we just proved in Session stores, cookies, and dirty tracking: touching "request immediately fires a session read and adds "Vary: Cookie". If AuthenticationMiddleware loaded the logged-in user inside process_request, every view in your application — including public JSON endpoints and cached marketing pages — would hit both "django_session" and "auth_user" and lose shared proxy caching!
Why the user attribute is a SimpleLazyObject (and async under ASGI)
Open AuthenticationMiddleware:
request.user = SimpleLazyObject(lambda: get_user(request))
request.auser = partial(auser, request)
First it asserts that SessionMiddleware ran earlier (hasattr(request, "session"), raising ImproperlyConfigured if your "MIDDLEWARE" order is reversed). Then it attaches two lazy hooks without executing a single SQL query:
"request.user": ASimpleLazyObjectwhose internal"_wrapped"slot starts as the sentinelempty. Until code inspects an attribute like"requestor.user .is_authenticated" "request, the closure never runs,.user .username" "requeststays.session .accessed" False, and zero database queries fire. On first access,SimpleLazyObjectruns._setup get_user, caches the result on"request, and forwards all subsequent lookups straight to the concrete._cached_user" UserorAnonymousUser."request.auser": Afunctoolswrapping the async coroutine.partial auser(cached on"request). Because Python property access cannot be._acached_user" awaited, async views under ASGI call"user = await request— invoking.auser()" aget_user, which reads the session via"await requestand fetches the user via.session .aget(...)" "await backendwithout tripping.aget_user(user_id)" SynchronousOnlyOperation!
User resolution, login rotation, and the session auth hash
When "request.user" is finally touched, get_user resolves identity in three strict steps:
- Read session keys: Reads
SESSION_KEY(SESSION_KEY,"_auth_user_id") andBACKEND_SESSION_KEY(BACKEND_SESSION_KEY,"_auth_user_backend"), verifying that"backend_path"is still listed in"settings..AUTHENTICATION_BACKENDS" - Fetch user from the recording backend: Loads that specific backend and calls
"backend(.get_user(user_id)" 2SQL queries total:"django_session"then"auth_user"). - Verify
HASH_SESSION_KEY: CallsAbstractBaseUser, which computes a SHA-256.get_session_auth_hash salted_hmacoverAbstractBaseUserusing.password "SECRET_KEY", and compares it against"requestvia.session['_auth_user_hash']" constant_time_compare. If"SECRET_KEY"recently rotated, Django also checks"SECRET_KEY_FALLBACKS"(AbstractBaseUser) and upgrades the stored hash transparently. If neither matches — most commonly because the user’s password was changed —.get_session_auth_fallback_hash get_userimmediately calls"requestand returns.session .flush()" AnonymousUser()!
That cryptographic tie between the session and the stored password hash means changing a password automatically invalidates every stolen or forgotten session across all devices without needing a separate session-to-user lookup table! (And it is why password-change views must call update_session_auth_hash to cycle the current session key and refresh "_auth_user_hash" so the user who changed their own password stays logged in.)
Look too at what login does before writing those three "_auth_user_*" keys:
- If the incoming session was anonymous,
logincalls"request— issuing a brand-new random session ID while preserving anonymous session data (like a shopping cart or draft note), defeating session-fixation attacks!.session .cycle_key()" - If the incoming session already belonged to a different authenticated user (or had a stale auth hash),
logincalls"requestinstead so User A’s private session keys can never leak into User B’s login..session .flush()" - Finally,
logincallsrotate_tokento rotate the CSRF secret across the privilege boundary, replaces"request.user"and"request.auser", and firesuser_logged_in.
Watch login cycle the session key and rotate CSRF while keeping anonymous data, AuthenticationMiddleware remain at 0 SQL queries before "request.user" is touched, and a password change flush the old session live on "desk/":
2. AuthenticationMiddleware SimpleLazyObject and HASH_SESSION_KEY
login_rotation: session_key_cycled=True csrf_rotated=True anon_data_preserved=True keys=['_auth_user_backend', '_auth_user_hash', '_auth_user_id']
before_access: sql=0 wrapped_is_empty=True has_auser=True
after_access: sql=2 wrapped_type=User username='editor'
password_change: hash_changed=True old_session_user=AnonymousUser is_authenticated=False session_flushed=True
Notice how "after_access" paid 2 SQL queries ("django_session" + "auth_user"), and how changing "editor"'s password flipped "get_session_auth_hash()" and instantly downgraded the old session cookie to AnonymousUser with "session_flushed=True".
Sessions remember who already logged in. Next we trace the login moment itself — how authenticate walks backends, why Django 6.1 burns 1,500,000 PBKDF2 iterations even for nonexistent usernames, and how legacy hashes upgrade silently in Authentication backends and hash upgrades.