The machineryHow 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 attaches a lazy SessionBase store that avoids database reads until touched and stamps "Vary: Cookie" the moment anything reads it. AuthenticationMiddleware wraps user resolution in a SimpleLazyObject, verifies 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 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, ChangeList, and ModelAdmin._changeform_view.
From an opaque cookie to SimpleLazyObject without wasted queries
Figure 11.1 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 6.1’s 1,500,000-iteration PBKDF2PasswordHasher, timing-attack mitigation, and transparent hash upgrades, followed by PermissionsMixin per-instance caching and ContentTypeManager.
Then we open the largest application shipped inside Django itself — django.contrib.admin — tracing AdminConfig autodiscovery and 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 save a "Story", its "CorrectionInline" formset, and a JSON LogEntry inside one django.db.transaction.atomic block.