The Auth System: Users, Login and Password Storage

The Auth System: Users, Login and Password Storage in Django: A specialist locksmith serves a building with hundreds of doors.

The Analogy: A Locksmith Who Keeps Impressions, Never Copies of Keys

A specialist locksmith serves a building with hundreds of doors. When a tenant enrols, the locksmith deliberately does not keep a copy of their key. A drawer full of working copies is a catastrophe waiting to happen: steal the drawer and you own every door. Instead the locksmith takes a one-way impression, a hardened casting that can confirm whether a key pressed into it matches, but from which no working key can ever be cut. The original key goes home in the tenant's pocket. Only the impression stays behind, and an impression opens nothing.

Two tenants might, by chance, carry identically cut keys. To keep their records from looking the same, the locksmith mixes a unique grit into each casting compound, so even identical keys leave visibly different castings, and one stolen casting tells a thief nothing about any other. The compound is also chosen to set slowly and to be read only under a calibrated press. You cannot rush thousands of trial keys through it in an afternoon. That slowness is worthless to a patient tenant checking one key and ruinous to a thief trying millions.

The shop keeps improving its compound. When a tenant returns and their key matches an old casting, the locksmith quietly re-takes the impression in the newest compound, so the records upgrade themselves as people come and go. Keys that are trivially copyable, a raw blank or a known master pattern, are refused at enrolment rather than cast at all. And the shop draws a hard line between two separate acts: confirming that a key matches a casting, and issuing the day's wristband that the door guards actually honour. The first proves who you are. The second is what gets you through the turnstiles until you hand it back on the way out.

The failure mode is a receptionist who, turning someone away, tells them exactly why. "We have no casting under that name" instead of a flat "that key did not match" quietly hands a stranger a roster of who is and is not enrolled, the first thing anyone planning to force a door would want. Worse is the shop that, to save time, starts keeping working copies again "just for the difficult locks." The moment that drawer is opened, every door it covers is open too. The one-way impression was the entire point, and a single shortcut back to storing the real key throws away every other protection at once.


Syntax or Core Structure

Django never stores the password. It stores a verifier: a salted, deliberately slow hash from which the password cannot be recovered. create_user and set_password produce that verifier; check_password re-hashes a candidate with the stored salt and compares. The toy stand-in below keeps the shape (algorithm, salt, digest, one-way check) while using whole-number arithmetic so the output is exact.

from django.contrib.auth import get_user_model

User = get_user_model()

# create_user hashes the password; create() would store it verbatim and break login.
user = User.objects.create_user(username="ada", password="s3cret-not-in-source")
user.set_password("a-new-one")   # hashes in memory
user.save()                      # forgetting this silently discards the change
user.check_password("a-new-one") # True

The stand-in models the same one-way check. digest folds the characters into a number and mixes in the salt, make_hash records algorithm, salt, and digest as one string, and verify re-derives the digest from a candidate. Two users with the same password get different stored strings because their salts differ.

def digest(salt, raw):
    total = 0
    for ch in raw:
        total = total * 31 + ord(ch)
    return (total + salt * 7) % 1000000


def make_hash(salt, raw):
    return "toy$" + str(salt) + "$" + str(digest(salt, raw))


def verify(stored, candidate):
    algo, salt, dig = stored.split("$")
    return digest(int(salt), candidate) == int(dig)


ada = make_hash(11, "hunter2")
bob = make_hash(29, "hunter2")

print("ada stored:  " + ada)
print("bob stored:  " + bob)
print("same password, same stored: " + str(ada == bob))
print("ada verifies hunter2: " + str(verify(ada, "hunter2")))
print("ada verifies wrong:   " + str(verify(ada, "guess")))

Output:

ada stored:  toy$11$137279
bob stored:  toy$29$137405
same password, same stored: False
ada verifies hunter2: True
ada verifies wrong:   False

Two identical passwords produce two different stored strings, so a stolen record leaks nothing about anyone else, and a correct candidate verifies while a wrong one does not. The real hasher is vastly stronger, but the contract is identical: the stored value proves a password without being the password. User.objects.create(password="hunter2") skips make_hash entirely and stores the literal string, after which every login fails because the verifier compares a candidate's digest against something that was never a digest.


Technical Depth: Storage, Validation, and the Two-Step of Logging In

The flags that decide what an account can do

Three boolean fields on the user are routinely misread, and each mistake grants either too much or too little.

FlagGrantsDoes not grant
is_activemay authenticate at allany sense of being online right now
is_staffmay open the admin sitepowers over data once inside it
is_superuserbypasses every permission checkstaff status, so set both for admin

Setting is_active = False is the correct way to lock an account out: the default backend refuses to authenticate an inactive user, so deactivation is an immediate lockout without deleting any history.

Validators reject weak secrets before they are stored

AUTH_PASSWORD_VALIDATORS is the enrolment gate that refuses trivially guessable keys. Each validator blocks a different weak pattern, and they run in forms and in validate_password(), but not inside set_password(), so a data import that calls set_password directly bypasses the whole policy.

ValidatorBlocks
MinimumLengthValidatorsecrets under the length floor
CommonPasswordValidatorthe guesses a stuffing attack tries first
NumericPasswordValidatorall-digit secrets
UserAttributeSimilarityValidatorsecrets built from the username or email
COMMON = ["password", "hunter2", "123456", "qwerty"]


def validate(raw, username):
    errors = []
    if len(raw) < 12:
        errors.append("too short (min 12)")
    if raw.lower() in COMMON:
        errors.append("too common")
    if raw.isdigit():
        errors.append("all numeric")
    if username.lower() in raw.lower():
        errors.append("too similar to username")
    return errors


def try_set(username, raw):
    errs = validate(raw, username)
    if errs:
        return "REJECT " + raw + ": " + "; ".join(errs)
    return "OK " + raw


print(try_set("ada", "correct-horse-battery"))
print(try_set("ada", "hunter2"))
print(try_set("ada", "123456789012"))
print(try_set("ada", "ada-private-key"))

Output:

OK correct-horse-battery
REJECT hunter2: too short (min 12); too common
REJECT 123456789012: all numeric
REJECT ada-private-key: too similar to username

The long passphrase passes; the short common word, the all-digit string, and the username-derived value are each turned away with a specific reason for the developer. Favouring length over composition rules is deliberate: a twelve-character passphrase carries more entropy than "P@ss1!" and is far likelier to survive contact with a real person than a rule that guarantees a sticky note on the monitor.


Real World Example: A Sign-In Flow That Refuses to Leak

Authentication is two acts kept deliberately separate: prove the key matches (verify), then issue the wristband the rest of the app honours (a session). The flow below stores three users, one of them inactive and one still on an old unsalted verifier, and processes a run of sign-in attempts. Every failure, whatever its true cause, returns one identical message, and a successful login on the old verifier transparently re-stores it with a salt.

SESSIONS = {}
NEXT_TOKEN = 500


def digest(salt, raw):
    total = 0
    for ch in raw:
        total = total * 31 + ord(ch)
    return (total + salt * 7) % 1000000


def make_hash(salt, raw):
    return "toy$" + str(salt) + "$" + str(digest(salt, raw))


def verify(stored, raw):
    algo, salt, dig = stored.split("$")
    return digest(int(salt), raw) == int(dig)


USERS = {
    "ada":  {"stored": make_hash(11, "correct-horse"), "active": True},
    "bob":  {"stored": "old$0$" + str(digest(0, "sunflower-42")), "active": True},
    "cara": {"stored": make_hash(23, "winter-garden"), "active": False},
}

def login(username, password):
    global NEXT_TOKEN
    rec = USERS.get(username)
    if rec is None or not verify(rec["stored"], password):
        return "Invalid credentials."
    if not rec["active"]:
        return "Invalid credentials."
    note = ""
    if rec["stored"].startswith("old$"):
        rec["stored"] = make_hash(11, password)
        note = " (hash upgraded)"
    token = NEXT_TOKEN
    NEXT_TOKEN = NEXT_TOKEN + 1
    SESSIONS[token] = username
    return "OK token=" + str(token) + note


ATTEMPTS = [
    ("ada", "correct-horse"),
    ("ada", "wrong"),
    ("mallory", "whatever"),
    ("cara", "winter-garden"),
    ("bob", "sunflower-42"),
    ("bob", "sunflower-42"),
]
for username, password in ATTEMPTS:
    print(username.ljust(8) + " " + login(username, password))
print("sessions: " + str(len(SESSIONS)))

Output:

ada      OK token=500
ada      Invalid credentials.
mallory  Invalid credentials.
cara     Invalid credentials.
bob      OK token=501 (hash upgraded)
bob      OK token=502
sessions: 3

Read the log against the attempt list. Ada's first attempt matches her stored impression, so she receives token 500 and a row appears in SESSIONS. Her second attempt sends the wrong secret; verify recomputes the digest, finds no match, and returns the same flat refusal. The call for mallory never finds a record at all, and cara's secret is correct yet her account is inactive, so both are turned away with wording identical to a wrong password. Bob's stored value still carries the old$ prefix from a legacy import; his first login verifies against that legacy form, is immediately re-stored under the current scheme, and is tagged as upgraded, which is why his second identical login verifies against the new impression and simply issues another token. Three successful calls leave three rows in SESSIONS.

Three things this flow gets right are worth naming. First, every rejection -- unknown user, wrong secret, inactive account -- returns the byte-for-byte same string, so an attacker cannot mine the response to learn which usernames exist or which accounts are merely disabled. Second, the inactive check still refuses even when the secret is correct, so a suspended account grants nothing. Third, the legacy old$ record is upgraded the first time its owner logs in successfully, with no password-reset e-mail and no user-visible step, which is exactly how Django migrates a site onto a stronger hasher over time. Issuing the session token is a separate, later step from checking the secret, mirroring the split between authenticate and login.

The flaws here are precisely the parts you must not copy into production. The toy digest is a fast, reversible integer mix with a tiny output space; a real deployment relies on Django's deliberately slow, salted PBKDF2 or Argon2 hashers, because speed is the attacker's friend the moment a database leaks. The unknown-user branch returns before any digest is computed, so an adversary timing responses could distinguish a missing account from a wrong secret -- a leak this code closes in message text but not in elapsed time; Django hashes a throwaway password on the miss path specifically to flatten that timing. SESSIONS and NEXT_TOKEN are module-level globals mutated without locking, so two simultaneous logins could hand out the same token; a real session backend is transactional and keyed by an unguessable random string, not a sequential integer an attacker can count up through. And nothing here rate-limits attempts, so the flat refusal does nothing to slow a brute-force run.


Common Mistakes

  1. Setting the password field directly stores plaintext and breaks login. User.objects.create(username="ada", password="hunter2") writes the literal string into the column instead of a hash, so check_password can never match it and every login fails -- while the raw secret sits in the database in the clear. Create accounts with User.objects.create_user(...), which runs the secret through the configured hasher, or set it afterward with set_password.
  1. Calling set_password without saving leaves the change in memory only. user.set_password("new-secret") updates the in-memory instance but touches nothing in the database until you call user.save(). Forget the save and the next request loads the old hash, the user is baffled that their new password is rejected, and there is no error to point at. Always follow set_password with save(), or use a form or serializer that does it for you.
  1. Inventing your own hashing scheme is slower to build and faster to crack. A hand-rolled digest -- an MD5, a single SHA-256, anything unsalted or fast -- lets an attacker who steals the table brute-force millions of guesses per second, and identical passwords produce identical hashes that betray shared secrets across accounts. Django's default PBKDF2 and Argon2 hashers are salted and deliberately slow for exactly this reason; lean on them instead of reinventing the primitive.
  1. Different error messages for "no such user" and "wrong password" leak your user list. If a login form says "unknown username" for one case and "incorrect password" for the other, an attacker submits a list of candidate names and reads back which ones exist -- a free enumeration of your accounts, and often of who is a customer. Return one generic message, such as "Please enter a correct username and password," for every failure mode, exactly as Django's AuthenticationForm does.
  1. Assigning a password through set_password quietly skips the validators. set_password hashes whatever it is given; it does not run AUTH_PASSWORD_VALIDATORS. Code that sets passwords outside a form -- an admin action, a bulk import, a "reset to temporary" script -- can therefore store "123456" without complaint. Call validate_password(raw, user) yourself before set_password on any path that does not run through a form or serializer that already validates.
  1. Putting LoginRequiredMixin after the view base class disables the guard. Python resolves mixins left to right, so class InvoiceList(ListView, LoginRequiredMixin) lets ListView.dispatch run first and the login check never fires. The mixin must come first: class InvoiceList(LoginRequiredMixin, ListView). The page looks protected in review and quietly serves data to anonymous users in production.
  1. Treating "logged in" as "allowed" ships every user everyone's data. Authentication proves who is calling; it says nothing about which rows they may see. A view guarded only by login_required that then returns Invoice.objects.all() hands each authenticated user the whole table. Scope every query to the caller -- Invoice.objects.filter(owner=request.user) -- so authentication and authorization are both enforced.
  1. Redirecting to a raw next value turns your login into an open redirect. Sending the user to whatever request.GET["next"] contains lets an attacker craft a link like /login/?next=https://evil.example/phish and bounce your freshly authenticated victim to a look-alike site. Validate the target with url_has_allowed_host_and_scheme, as Django's own login view does, and fall back to a safe default when the check fails.
  1. Confusing is_staff, is_superuser, and is_active grants the wrong access. is_staff only opens the admin site's door; it grants no model permission on its own. is_superuser bypasses every permission check, so handing it out casually is a standing risk. Setting is_active to False is the correct way to disable an account -- deleting the row orphans its foreign keys. Read each flag for exactly what it controls before you set it in code.

Best Practices

  • Create and change passwords only through create_user and set_password. These are the only paths that run the raw secret through the configured hasher; never assign the password field directly. For self-service flows, let a form or serializer own the round trip so hashing, validation, and save happen together.
  • Keep Django's default salted, slow hashers and let login upgrade them. Leave PASSWORD_HASHERS at its secure default -- PBKDF2, or Argon2 once installed -- with your strongest hasher first in the list; Django then transparently re-hashes each user on their next successful login, migrating the whole table without a reset campaign.
  • Enforce AUTH_PASSWORD_VALIDATORS and favour length over character rules. Turn on the built-in validators and raise MinimumLengthValidator well past its default; a long passphrase resists guessing far better than a short string padded with symbols. Length is the cheapest strength you can require.
  • Run validate_password on any code path that sets a secret outside a form. Admin actions, imports, and management commands bypass form validation, so call validate_password(raw, user) explicitly before set_password there. It keeps a single source of truth for what counts as an acceptable password.
  • Fail every login with one message, and confirm resets without confirming accounts. Return an identical error for unknown users, wrong passwords, and inactive accounts, and word password-reset responses as "if that address exists, we have sent a link" so the page never reveals which addresses are registered.
  • Use authenticate, login, and logout, and disable accounts with is_active. Verify with authenticate, establish the session with login, end it with logout, and set is_active to False to lock an account instead of deleting it -- deletion cascades into related rows you probably meant to keep.
  • Pair authentication with per-user query scoping. A login guard is not access control; filter every queryset by request.user, or by an explicit object permission, so that being signed in never means seeing someone else's rows. Authentication and authorization are two separate jobs and both are yours.
  • Whitelist redirect targets and keep login URLs in settings. Validate any next parameter with url_has_allowed_host_and_scheme before redirecting, and configure LOGIN_URL, LOGIN_REDIRECT_URL, and LOGOUT_REDIRECT_URL centrally rather than hardcoding paths in views, so the safe defaults apply everywhere.

Practice Exercises

  1. Prove the no-enumeration property. Take the login function from the Real World example and write three assertions showing that an unknown user, a wrong password, and an inactive-but-correct account all return the exact same string. Then add a fourth account that is active with a correct password and assert it returns a token, so your test also proves a real login still succeeds.
  1. Add the missing timing defence. The unknown-user branch returns before any digest is computed. Change login so that on a miss it still runs verify against a fixed dummy stored value before returning the generic refusal, and write a comment explaining why doing equal work on both paths matters even though the message was already identical.
  1. Enforce validators on a non-form path. Write a set_or_reject(user, raw) helper that runs a small validator list -- minimum length 12, reject an all-numeric secret, reject one equal to the username -- and only then calls the stand-in's make_hash, returning the list of violations when any fire. Feed it four secrets (one good, one too short, one all digits, one equal to the username) and print the outcome for each.
  1. Turn a legacy hash into an upgrade path. Seed a user whose stored value uses the old$ prefix, log in successfully once, and assert that the stored value afterward no longer starts with old$ and that a second login still verifies. Then add a user whose stored value is plaintext with no prefix and show that login fails, mirroring the real bug where User.objects.create(password=...) was used by mistake.