Permissions, Groups and Session Security

Permissions, Groups and Session Security in Django: A large trade show fills a convention center for three days.

The Analogy: A Convention Center Issuing Tiered Badges and Fresh Lanyards

A large trade show fills a convention center for three days. Every hall, workshop room, exhibitor floor and speakers' green room has a reader on the door. What a badge opens is not decided by the holder's name, nor by their word at the door; it is decided by a set of encoded entitlements chipped into the badge itself. A reader either finds the entitlement for that door or it does not, and if it does not the door stays shut. One entitlement, one door.

Encoding thousands of badges door by door would be hopeless, so the registration desk works from a short list of categories. Attendee, Exhibitor, Speaker, Press: each is a pre-agreed bundle of entitlements settled once with the organizers. Check someone in under a category and every entitlement in that bundle rides along automatically. A person can hold more than one category at once, and their badge simply carries the union of every bundle they belong to. Better still, if the organizers decide halfway through that all Exhibitors may now enter the catering lounge, they change the one bundle and every exhibitor is covered, without re-encoding a single badge by hand.

The badge itself is deliberately temporary. It is printed and chipped with a fresh serial when the holder checks in at the desk, tied to that day, and voided at close so that yesterday's badge opens nothing this morning. Crucially, the serial is bound to the moment of check-in: when a walk-in visitor later upgrades to a full delegate at the members' desk, the clerk voids the old serial and issues a brand-new one rather than promoting the strip already in the visitor's hand. The credential you carry after you have proved who you are is never the same strip you were carrying before.

The failure is a desk under pressure that skips that last step. To clear a long queue, a clerk hands newcomers badges pre-chipped the night before from a printed list of serials, or lets a smiling stranger by the door press a spare badge into a newcomer's hand. Whoever kept a note of that serial now shares the newcomer's access all day, and because the serial was never reissued when the newcomer upgraded at the members' desk, the eavesdropper is silently promoted right alongside them. The badge was fixed by someone else before the holder ever proved their identity, and nothing rotated it afterward.


Syntax or Core Structure

Django gives every model four permissions automatically the moment it is migrated: add, change, delete and view, each named <app>.<verb>_<model>. You check one with user.has_perm("billing.view_invoice"), and you can define more of your own in a model's Meta.permissions. A user holds a permission in one of three ways: granted directly, inherited from a Group they belong to, or held implicitly because they are a superuser (for whom has_perm always returns True). The stand-in below reduces that resolution to a plain function so the logic is visible.

# billing/models.py -- a custom permission beyond the automatic four
class Invoice(models.Model):
    amount = models.PositiveIntegerField()

    class Meta:
        permissions = [("approve_invoice", "Can approve an invoice")]


# accounts setup -- a group is a reusable bundle of permissions
editors = Group.objects.create(name="editors")
editors.permissions.set([view_invoice, change_invoice])
ada.groups.add(editors)

Migrating Invoice creates add_invoice, change_invoice, delete_invoice and view_invoice on its own; the Meta.permissions entry adds approve_invoice. The Group named editors carries two of those permissions, and adding ada to the group hands her both without touching her own record. When code later asks ada.has_perm("billing.approve_invoice"), Django takes the union of her direct permissions and every group's permissions (and short-circuits to True for a superuser). The following plain-Python model computes that same union so you can watch it resolve.

PERMS_BY_GROUP = {
    "editors": ["view_invoice", "change_invoice"],
    "approvers": ["view_invoice", "approve_invoice"],
}


def effective(user):
    if user.get("is_superuser"):
        return "ALL"
    perms = list(user.get("direct", []))
    for g in user.get("groups", []):
        for p in PERMS_BY_GROUP.get(g, []):
            if p not in perms:
                perms.append(p)
    return perms


def has_perm(user, perm):
    eff = effective(user)
    if eff == "ALL":
        return True
    return perm in eff


def summary(name, u):
    line = name.ljust(5)
    line = line + " view=" + str(has_perm(u, "view_invoice"))
    line = line + " approve=" + str(has_perm(u, "approve_invoice"))
    line = line + " delete=" + str(has_perm(u, "delete_invoice"))
    return line


ada = {"direct": [], "groups": ["editors"], "is_superuser": False}
bob = {"direct": ["delete_invoice"], "groups": ["editors", "approvers"], "is_superuser": False}
root = {"direct": [], "groups": [], "is_superuser": True}

print(summary("ada", ada))
print(summary("bob", bob))
print(summary("root", root))

Output:

ada   view=True approve=False delete=False
bob   view=True approve=True delete=True
root  view=True approve=True delete=True

ada belongs only to editors, so she can view and change but cannot approve or delete. bob carries a direct delete_invoice and belongs to both editors and approvers, so his effective set is the union of all three sources and every check passes. root is a superuser: has_perm returns True without consulting any list at all, which is exactly why superuser status is dangerous to hand out and why real permission logic must never be tested only against a superuser account.


Technical Depth: Where a Permission Lives, and Why Groups Beat Per-User Grants

Four verbs Django creates for every model

Run migrate and Django writes one row into the permission table for each of four actions on every model, plus any you declare yourself. The codename is mechanical, so you can predict it without looking it up.

PermissionCreated byWhat it guards
add_invoiceDjango, automaticallycreating a new invoice
change_invoiceDjango, automaticallyediting an existing invoice
delete_invoiceDjango, automaticallyremoving an invoice
view_invoiceDjango, automatically (since 2.1)reading an invoice in views and admin
approve_invoiceyou, in Meta.permissionsa domain action Django cannot guess

Three ways a user comes to hold a permission

A permission check succeeds if any one of these sources supplies it. That is why auditing "who can approve invoices" means looking at direct grants, group membership, and the superuser flag together, not just one list.

SourceHow it is grantedReach
Direct grantuser.user_permissions.add(perm)that one user only
Group membershipuser.groups.add(group), and the group holds the permevery current member at once
Superuseruser.is_superuser set to Trueall permissions, with no lookup at all

The middle row is the one to lean on. Granting through a group means the rule lives in exactly one place, so changing what a role may do is a single edit that reaches every member on their next request. The demonstration below grants a new permission to a group and re-checks three users, one of whom gains the permission purely because their group changed.

GROUPS = {
    "editors": ["view_invoice", "change_invoice"],
    "approvers": ["view_invoice", "approve_invoice"],
}

USERS = {
    "ada": {"direct": [], "groups": ["editors"]},
    "bob": {"direct": ["delete_invoice"], "groups": ["editors", "approvers"]},
    "cara": {"direct": [], "groups": ["approvers"]},
}


def eff(name):
    u = USERS[name]
    perms = list(u["direct"])
    for g in u["groups"]:
        for p in GROUPS[g]:
            if p not in perms:
                perms.append(p)
    return perms


def can_approve(name):
    return "approve_invoice" in eff(name)


print("before: approve_invoice lives only in approvers")
for name in ["ada", "bob", "cara"]:
    print("  " + name.ljust(5) + str(can_approve(name)))

GROUPS["editors"].append("approve_invoice")

print("after: approve_invoice added to editors")
for name in ["ada", "bob", "cara"]:
    print("  " + name.ljust(5) + str(can_approve(name)))

Output:

before: approve_invoice lives only in approvers
  ada  False
  bob  True
  cara True
after: approve_invoice added to editors
  ada  True
  bob  True
  cara True

bob and cara could already approve, because both belong to approvers. The interesting line is ada: she flips from False to True without a single edit to her own record. The only change was to the editors bundle, and every member of editors inherited the new permission at once. That is the payoff of granting through groups instead of per user, and equally the reason a careless edit to a popular group can quietly widen access for hundreds of accounts.


Real World Example: A Session-Fixation Attack, With and Without Rotation

Permissions decide what an authenticated user may do; the session decides who the request is authenticated as in the first place. If an attacker can pin a known session identifier onto a victim before the victim logs in, then after the victim authenticates the attacker's copy of that identifier is authenticated too. Django defends against this automatically: its login() calls request.session.cycle_key(), which issues a fresh session key at the moment of authentication and abandons the old one. The program below models both a login that forgets to rotate and one that rotates, and runs the identical attack against each.

NEXT = 1000
SESSIONS = {}


def new_token():
    global NEXT
    token = NEXT
    NEXT = NEXT + 1
    return token


def start_session():
    token = new_token()
    SESSIONS[token] = {"user": None}
    return token


def login_insecure(token, user):
    # reuses the id the client already presented -- vulnerable to fixation
    SESSIONS[token] = {"user": user}
    return token


def login_secure(token, user):
    # rotate: drop the pre-auth id, issue a fresh one (cycle_key)
    if token in SESSIONS:
        del SESSIONS[token]
    fresh = new_token()
    SESSIONS[fresh] = {"user": user}
    return fresh


def who(token):
    rec = SESSIONS.get(token)
    if rec is None:
        return "none"
    if rec["user"] is None:
        return "anonymous"
    return rec["user"]


def run(mode):
    global SESSIONS
    SESSIONS = {}
    login = login_insecure if mode == "insecure" else login_secure
    planted = start_session()
    active = login(planted, "victim")
    rides = planted == active and who(planted) == "victim"
    print(mode + ":")
    print("  planted token seen as: " + who(planted))
    print("  active token seen as:  " + who(active))
    print("  attacker rides in:     " + str(rides))


run("insecure")
run("secure")

Output:

insecure:
  planted token seen as: victim
  active token seen as:  victim
  attacker rides in:     True
secure:
  planted token seen as: none
  active token seen as:  victim
  attacker rides in:     False

Read the two runs side by side. In both, start_session() mints token 1000 and files it under an anonymous record -- this is the id an attacker plants in the victim's browser before they ever log in. Then the victim authenticates. The insecure login writes the victim's name straight onto token 1000, so the planted id and the active id are the same integer and both resolve to victim; the attacker, still holding 1000, is now signed in as the victim. The secure login deletes 1000 the instant credentials check out and hands back a fresh 1001, so the planted id resolves to none while only the (attacker-unknown) 1001 carries the victim -- planted == active is false and the ride-in check fails.

What the secure path models correctly is exactly what Django's login() does through request.session.cycle_key(): it discards the pre-authentication session identifier and issues a new one at the moment privilege rises, so any id captured before login is worthless after it. Three details make the demo honest. The pre-auth key is really removed (del SESSIONS[token]), not merely shadowed, so a later who(planted) genuinely returns none. The identity a token maps to is looked up through who() rather than read off the token integer, mirroring how a real session id is an opaque handle into server-side state, not a carrier of the user's name. And rotation is tied to the authentication event itself, which is the only place fixation can be closed.

The program is still a teaching model, and its shortcuts are the security holes. Tokens are sequential integers -- 1000, 1001, 1002 -- so an attacker who sees one can guess the next; real session keys are long high-entropy random strings precisely so they cannot be enumerated. Nothing here models the cookie that would actually carry the key, so the flags that stop theft in the first place -- Secure (HTTPS only), HttpOnly (hidden from JavaScript), and SameSite (not sent cross-site) -- are absent. There is no expiry and no idle timeout, so a token, once minted, lives forever. SESSIONS is an in-process dict, meaning every worker restart logs everyone out and no second server can see the same sessions -- a production backend is a shared cache or database table. And logout is never shown: a complete implementation flushes the session on sign-out so the key cannot be replayed after the user leaves.


Common Mistakes

  1. Confusing authentication with authorization. request.user.is_authenticated only says someone logged in; it says nothing about what they may do. Gating an approval action on authentication alone lets any signed-in account approve invoices. Guard the action with has_perm("invoices.approve_invoice") instead.
  1. Granting every permission directly to individual users. Direct grants scatter policy across thousands of user rows, and onboarding a new editor means remembering the exact set by hand. Put the permissions on a Group once and add users to it; when the policy changes you edit one bundle, not every account.
  1. Expecting custom permissions to exist before you migrate. A Meta.permissions entry and the four default verbs are written to the auth_permission table by the migration, not by defining the model. user.has_perm("app.approve_invoice") returns False for everyone until migrate has run, and assigning a not-yet-created permission raises DoesNotExist.
  1. Testing permission logic while logged in as a superuser. is_superuser short-circuits has_perm to True for every permission, existing or not, so a superuser is the one account that can never reveal a missing grant. Every check looks like it passes, and the gap only surfaces in production for an ordinary user. Test with a normal account that holds exactly the groups under test.
  1. Not knowing that permissions are cached for the request. The first has_perm call loads and caches the user's permissions on the instance (_perm_cache), so a group change you make later in the same request is invisible until you refetch the user or clear the cache. Long-lived worker processes that hold a user object across requests can serve stale permissions the same way.
  1. Leaving the session id unchanged across login. If authentication reuses the pre-auth session key, an attacker who fixed that key in the victim's browser is signed in the moment the victim is. Django's login() rotates the key for you via cycle_key(); hand-rolled auth that writes the user onto the existing session reopens the hole.
  1. Never flushing the session on logout. Clearing your own reference to the user without calling logout() (which runs session.flush()) leaves the server-side record and its key alive, so anyone replaying the old cookie is still signed in. Log out on the server, do not merely drop the cookie on the client.
  1. Treating session contents as secret because they are "server-side". With the default signed-cookie session backend the payload rides in the client's cookie: it is tamper-evident, not encrypted, so the user can read every key you stored. Keep secrets in a database-backed or cache-backed session, or do not put them in the session at all.
  1. Shipping session cookies without Secure, HttpOnly, and SameSite. A cookie without Secure leaks over plain HTTP, without HttpOnly is readable by injected JavaScript, and without SameSite is sent on cross-site requests. The most careful rotation logic is moot if the key it protects is trivially stolen from the browser.

Best Practices

  • Model authority as groups and assign users to groups. Treat a Group as a named role -- Editors, Approvers, Auditors -- and grant permissions to the role, never to people. Membership then becomes the only thing that varies per user, and a policy change is a single edit to one bundle.
  • Check the specific permission, not membership or authentication. Write user.has_perm("invoices.approve_invoice"), not user.groups.filter(name="approvers") or a bare is_authenticated. Use PermissionRequiredMixin on class views and @permission_required on function views so the check is declarative and impossible to forget.
  • Let Django's login() rotate the session for you. It calls cycle_key() to issue a fresh key at authentication and abandon the pre-auth one, which is the fix for session fixation. Do not hand-roll auth that writes the user onto the existing session id.
  • Set the cookie security flags explicitly in settings. Turn on SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE, keep SESSION_COOKIE_HTTPONLY = True, and set SESSION_COOKIE_SAMESITE = "Lax" (or "Strict"). These flags are what stop the key from leaking over HTTP, into JavaScript, or across sites.
  • Flush the session on logout and on any privilege change. Call logout() (which runs session.flush()) at sign-out, and rotate again when a user's role rises mid-session, so a captured key never outlives the trust that issued it.
  • Keep session payloads small and non-secret. Store an identifier and look the rest up server-side rather than stashing sensitive data in the session, especially under the default signed-cookie backend where the client can read every key.
  • Give sessions an expiry and an idle policy. Set SESSION_COOKIE_AGE to a sane lifetime and decide on SESSION_EXPIRE_AT_BROWSER_CLOSE; a token that never expires is a token an attacker has unlimited time to use.
  • Enforce authority at one choke point and re-check after group edits. Concentrate permission checks in middleware or a view mixin instead of scattering them, and remember the per-request _perm_cache: after changing a user's groups in the same request, refetch the user before relying on has_perm again.

Practice Exercises

  1. Consolidate direct grants into groups. Start from three users who each hold view_invoice, change_invoice, and approve_invoice as direct grants. Define two groups -- Editors (view + change) and Approvers (view + approve) -- move every user to the right group(s), and write a check that prints each user's effective permissions before and after. Prove the effective set is identical while the number of direct grants drops to zero.
  1. Add object-level checks. Extend the has_perm stand-in so a permission can be scoped to a single object (for example, "change_invoice on invoice 7 only"). Model per-object grants as (perm, object_id) pairs, keep the model-wide grants working, and show a user who may change invoice 7 but not invoice 8.
  1. Prove logout closes the session. Add logout(token) to the session demo so it deletes the record, then write a run that logs a user in on the secure path, calls logout, and shows who(active) returning none afterward. Confirm that replaying the old token no longer resolves to the user.
  1. Audit cookie flags. Given a settings dict with SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY, and SESSION_COOKIE_SAMESITE, write audit(settings) that returns one finding per unsafe flag (missing Secure, missing HttpOnly, SameSite of None without Secure). Run it over a hardened config (zero findings) and a sloppy one (three findings) and print the counts.