---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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](sessions.md): touching `"request.session"` immediately fires a session read and adds `"Vary: Cookie"`. If `AuthenticationMiddleware` (`django/contrib/auth/middleware.py: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` (`django/contrib/auth/middleware.py:AuthenticationMiddleware.process_request`):

```python
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"`:** A **`SimpleLazyObject`** (`django/utils/functional.py:SimpleLazyObject`) whose internal `"_wrapped"` slot starts as the sentinel `empty` (`django/utils/functional.py:empty`). Until code inspects an attribute like `"request.user.is_authenticated"` or `"request.user.username"`, the closure never runs, `"request.session.accessed"` stays `False`, and zero database queries fire. On first access, `SimpleLazyObject._setup` runs `django/contrib/auth/middleware.py:get_user`, caches the result on `"request._cached_user"`, and forwards all subsequent lookups straight to the concrete `User` or `AnonymousUser` (`django/contrib/auth/models.py:AnonymousUser`).
- **`"request.auser"`:** A `functools.partial` wrapping the async coroutine `django/contrib/auth/middleware.py:auser` (cached on `"request._acached_user"`). Because Python property access cannot be `await`ed, async views under ASGI call `"user = await request.auser()"` — invoking `aget_user` (`django/contrib/auth/__init__.py:aget_user`), which reads the session via `"await request.session.aget(...)"` and fetches the user via `"await backend.aget_user(user_id)"` without tripping `SynchronousOnlyOperation`!

## User resolution, `login` rotation, and the session auth hash

When `"request.user"` is finally touched, `django/contrib/auth/__init__.py:get_user` resolves identity in three strict steps:

1. **Read session keys:** Reads `SESSION_KEY` (`django/contrib/auth/__init__.py:SESSION_KEY`, `"_auth_user_id"`) and `BACKEND_SESSION_KEY` (`django/contrib/auth/__init__.py: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` (`django/contrib/auth/__init__.py:HASH_SESSION_KEY`):** Calls `AbstractBaseUser.get_session_auth_hash` (`django/contrib/auth/base_user.py: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` (`django/utils/crypto.py: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` (`django/contrib/auth/__init__.py: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` (`django/contrib/auth/__init__.py:login`) does before writing those three `"_auth_user_*"` keys:

- If the incoming session was anonymous, `login` calls `"request.session.cycle_key()"` — issuing a brand-new random session ID while **preserving** anonymous session data (like a shopping cart or draft note), defeating session-fixation attacks!
- If the incoming session already belonged to a *different* authenticated user (or had a stale auth hash), `login` calls `"request.session.flush()"` instead so User A's private session keys can never leak into User B's login.
- Finally, `login` calls `rotate_token` (`django/middleware/csrf.py:rotate_token`) to rotate the CSRF secret across the privilege boundary, replaces `"request.user"` and `"request.auser"`, and fires `user_logged_in` (`django/contrib/auth/signals.py:user_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/"`:

```text recording=ch11-auth
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](backends-and-passwords.md).
