---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: Presentation and systems
promise: The user is just request.user.
contents: sessions, lazy-user, backends-and-passwords, permissions, admin-registry, changelist, changeform
---

# Sessions, auth, and the admin

How session cookies map to backends, how `AuthenticationMiddleware` defers database work behind a `LazyObject`, and how the Admin exercises every internal layer of Django at once.

From a view, authentication looks like a free attribute on every request: check `"request.user.is_authenticated"`, ask `"request.user.has_perm('newsroom.change_story')"`, or open `"/admin/"` and watch Django conjure an entire CRUD interface out of five registered models.

Open the source and that single attribute unfolds into a carefully staged chain of lazy proxies, cryptographic hashes, per-instance caches, and dynamic URL trees. `SessionMiddleware` (`django/contrib/sessions/middleware.py:SessionMiddleware`) attaches a lazy `SessionBase` (`django/contrib/sessions/backends/base.py:SessionBase`) store that avoids database reads until touched and stamps `"Vary: Cookie"` the moment anything reads it. `AuthenticationMiddleware` (`django/contrib/auth/middleware.py:AuthenticationMiddleware`) wraps user resolution in a `SimpleLazyObject` (`django/utils/functional.py:SimpleLazyObject`), verifies `HASH_SESSION_KEY` (`django/contrib/auth/__init__.py:HASH_SESSION_KEY`) against an HMAC of the user's password hash on every authenticated request, and leaves anonymous API views at zero database queries. `ModelBackend` (`django/contrib/auth/backends.py:ModelBackend`) defends login endpoints against timing-based username enumeration at `1,500,000` PBKDF2 iterations while silently upgrading older password hashes on login, and caches permissions directly on the user instance. Finally, `django.contrib.admin` stitches every layer of Chapters 1 through 10 together inside `AdminSite` (`django/contrib/admin/sites.py:AdminSite`), `ChangeList` (`django/contrib/admin/views/main.py:ChangeList`), and `ModelAdmin._changeform_view` (`django/contrib/admin/options.py:ModelAdmin._changeform_view`).

## From an opaque cookie to `SimpleLazyObject` without wasted queries

```text figure=session-and-lazy-user
Sessions, SimpleLazyObject, and session auth hash verification on desk/ (Django 6.1.3)

1. From sessionid cookie to request.user (lazy until first attribute access):
   SessionMiddleware -> SessionStore(key), 0 SQL in process_request; accessed -> Vary: Cookie
   AuthMiddleware    -> SimpleLazyObject(_wrapped is empty), 0 SQL on /api/stories/, auser() for ASGI
   Lazy get_user()   -> 2 SQL on first read: SELECT django_session + SELECT auth_user
   Hash verify       -> HASH_SESSION_KEY vs salted_hmac(password); mismatch -> session.flush()!

2. Verified session, login, and permission cache behavior on desk/:
   Session stores: untouched=0 SQL, read_only=1 SQL (Vary: Cookie), modified=3 SQL (Set-Cookie)
   login() safety: session_key cycled, CSRF token rotated, anon data kept
   Password/perms: password change flushes old session; has_perm() caches on User (stale mid-request!)
```

*Every SQL count, header, and rotation flag is verified directly against `ch11-auth`. Notice the two-layer laziness: `SessionMiddleware` does not load `"django_session"` until a key is read, and `AuthenticationMiddleware` does not read `"_auth_user_id"` until code actually touches `"request.user"` — keeping public endpoints like `"/api/stories/"` at zero auth queries even for logged-in browsers!*

## Identity and the Admin in seven stops

We start with `"SessionMiddleware"` and `"SessionBase"` dirty tracking, comparing database, cached-database, and signed-cookie session stores on `"desk/"`. Next we trace `"AuthenticationMiddleware"`, `SimpleLazyObject`, `"HASH_SESSION_KEY"` invalidation on password change, `"login()"` fixation defenses, and async `"request.auser()"`. From there we open `authenticate` (`django/contrib/auth/__init__.py:authenticate`), Django `6.1`'s `1,500,000`-iteration `PBKDF2PasswordHasher` (`django/contrib/auth/hashers.py:PBKDF2PasswordHasher`), timing-attack mitigation, and transparent hash upgrades, followed by `PermissionsMixin` (`django/contrib/auth/models.py:PermissionsMixin`) per-instance caching and `ContentTypeManager` (`django/contrib/contenttypes/models.py:ContentTypeManager`).

Then we open the largest application shipped inside Django itself — `django.contrib.admin` — tracing `AdminConfig` (`django/contrib/admin/apps.py:AdminConfig`) autodiscovery and `AdminSite.get_urls` (`django/contrib/admin/sites.py:AdminSite.get_urls`), dissecting an `80`-query `ChangeList` N+1 storm caused by a single custom `"list_display"` callable on `"StoryAdmin"`, and watching `ModelAdmin.changeform_view` (`django/contrib/admin/options.py:ModelAdmin.changeform_view`) save a `"Story"`, its `"CorrectionInline"` formset, and a JSON `LogEntry` (`django/contrib/admin/models.py:LogEntry`) inside one `django.db.transaction.atomic` block.

We begin at the cookie boundary in [Session stores, cookies, and dirty tracking](auth/sessions.md).
