Django 6.1.3

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.session" 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.process_request:

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:

User resolution, login rotation, and the session auth hash

When "request.user" is finally touched, get_user resolves identity in three strict steps:

  1. Read session keys: Reads SESSION_KEY (SESSION_KEY, "_auth_user_id") and BACKEND_SESSION_KEY (BACKEND_SESSION_KEY, "_auth_user_backend"), verifying that "backend_path" is still listed in "settings.AUTHENTICATION_BACKENDS".
  2. Fetch user from the recording backend: Loads that specific backend and calls "backend.get_user(user_id)" (2 SQL queries total: "django_session" then "auth_user").
  3. Verify HASH_SESSION_KEY: Calls AbstractBaseUser.get_session_auth_hash, which computes a SHA-256 salted_hmac over AbstractBaseUser.password using "SECRET_KEY", and compares it against "request.session['_auth_user_hash']" via constant_time_compare. If "SECRET_KEY" recently rotated, Django also checks "SECRET_KEY_FALLBACKS" (AbstractBaseUser.get_session_auth_fallback_hash) and upgrades the stored hash transparently. If neither matches — most commonly because the user’s password was changed — get_user immediately calls "request.session.flush()" and returns 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:

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/":

Recorded on Django 6.1.3 ch11-auth script
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.