Authentication, Permissions and Object-Level Access

Authentication, Permissions and Object-Level Access in Django: At the front desk of a national archive, a reader hands over a photo ID and a reader's card, and…

The Analogy: A Restricted-Access Archive Reading Room

At the front desk of a national archive, a reader hands over a photo ID and a reader's card, and the clerk checks them against the register of enrolled readers. That check answers exactly one question: who is this person? Satisfied, the clerk waves them through the turnstile into the reading room. Nothing about passing the turnstile entitles the reader to any particular document; it only establishes, on the record, that this is a known reader and not a stranger off the street.

The second gate is entirely separate, and it is the one people forget. Every manuscript box in the closed stacks has a call-slip register naming who may request it: some boxes are open to any reader, others are restricted to a named scholar or a single department. When a reader submits a call slip, the desk consults that register box by box. Being a valid, enrolled reader says nothing about whether this box is theirs to open. Treating the turnstile as if it also granted the documents is the classic confusion, and it is how restricted files walk out of buildings.

The stacks are closed by default, which is the quiet safeguard that makes the whole thing work. Nothing sits on an open shelf to be browsed; a reader cannot wander in and pull boxes. They submit a slip, and staff retrieve only the boxes the reader is entitled to, fetching against the reader's own entitlements rather than whatever shelf number the reader happened to scribble. Because retrieval is scoped to the reader, a restricted box is never even brought to the table, and the reader has no way to learn it exists. That is a stronger protection than refusing a box at the table, because refusing it confirms the box is real.

The failure mode is a harried clerk who, under a queue of impatient readers, stops consulting the register and simply fetches whatever box number is written on the slip. The register still exists; the clerk just trusts the number as if writing it down were the same as being entitled to it. A reader writes a box number that is not theirs, and the clerk hands over a restricted file without a second look. Nothing was hacked. The identity check at the turnstile passed honestly, and the entitlement check was skipped, because the clerk trusted a value the reader supplied.


Syntax or Core Structure

Two questions hide inside every protected endpoint, and conflating them is the most common API security failure. Authentication asks who is making this request; authorisation asks whether that identity may perform this action on this object. Being logged in is not permission to read invoice 4711. In DRF the two live in different hooks of a permission class.

from rest_framework import permissions


class IsOwner(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated

    def has_object_permission(self, request, view, obj):
        return obj.owner_id == request.user.id

The same two-gate logic, reduced to a plain Python REPL, makes the ordering visible. First we ask whether the caller is authenticated at all; only then do we ask whether this authenticated caller owns the specific object. An anonymous request never reaches the second question.

def is_authenticated(user):
    return user is not None

def has_object_permission(user, obj):
    return obj["owner_id"] == user["id"]

def access(user, obj):
    if not is_authenticated(user):
        return "401 unauthenticated"
    if not has_object_permission(user, obj):
        return "403 forbidden"
    return "200 ok"

ada = {"id": 1, "name": "Ada"}
bob = {"id": 2, "name": "Bob"}
invoice = {"id": 4711, "owner_id": 1}

CASES = [("ada", ada), ("bob", bob), ("anon", None)]
for label, user in CASES:
    print(label.ljust(4) + " -> " + access(user, invoice))

Output:

ada  -> 200 ok
bob  -> 403 forbidden
anon -> 401 unauthenticated

Read the three lines as the three outcomes that matter. Ada owns invoice 4711, so both gates open and she gets 200. Bob is a perfectly valid, authenticated user, and he is still refused with 403 because the object is not his: authentication passed, authorisation did not. The anonymous caller is stopped at the first gate with 401 and never reaches the ownership check at all. That ordering is deliberate; a 403 tells the caller the object exists but is not theirs, so you only want to emit it once you have decided the caller is even allowed to ask.


Technical Depth: Two Gates, and the List That Skips One

Authentication proves identity; permissions decide access

Authentication attaches an identity to the request; DRF ships several mechanisms for it, and the choice shapes your CSRF exposure. Session auth rides on a cookie the browser sends automatically, which is precisely the condition CSRF exploits, so unsafe methods still need the CSRF token. Header-based token and JWT auth do not attach themselves, so a cross-site page cannot silently authenticate as the user.

MechanismBest forSecurity note
Sessionsame-site web UIcookie-based, so CSRF protection applies
Tokenscripts, server-to-serversent in a header, no expiry by default
JWTmobile and SPA clientsstateless, needs refresh and rotation

Once identity is settled, permissions take over, and DRF checks them at two distinct moments. The confusion that leaks data is assuming a single check covers both.

One gate guards the endpoint, another guards the row

has_permission runs on every request before the view body and decides whether this user may use the endpoint at all. has_object_permission runs only when the view calls get_object(), and decides whether this user may touch one specific row. The gap between them is not academic: some actions call get_object() and some do not.

Actionhas_permissionhas_object_permissionqueryset scoping
listrunsdoes not runyour only guard
retrieverunsrunsalso applies
createrunsdoes not runnot applicable
updaterunsrunsalso applies
destroyrunsrunsalso applies

Read the list row carefully, because it is where object-level permissions quietly fail to protect anything.

The list endpoint skips the object gate

Because list never fetches a single object, has_object_permission never runs for it. A ModelViewSet protected only by an object-level IsOwner class will still list everybody's rows. The real protection for a list is scoping the queryset to the user. This stand-in shows both, side by side, over the same data.

INVOICES = [
    {"id": 4711, "owner_id": 1, "amount": 1500},
    {"id": 4712, "owner_id": 2, "amount": 900},
    {"id": 4713, "owner_id": 1, "amount": 400},
]

def list_unscoped(user):
    return [i["id"] for i in INVOICES]

def list_scoped(user):
    return [i["id"] for i in INVOICES if i["owner_id"] == user["id"]]

ada = {"id": 1}
print("unscoped: " + ",".join(str(x) for x in list_unscoped(ada)))
print("scoped:   " + ",".join(str(x) for x in list_scoped(ada)))

Output:

unscoped: 4711,4712,4713
scoped:   4711,4713

Unscoped, Ada sees all three invoices, including 4712 which belongs to Bob; the object permission that would have caught a single-row fetch was never consulted. Scoped, she sees only 4711 and 4713, her own rows, because the filter removed everyone else's before the view ever serialised them. Scoping is the stronger mechanism precisely because it applies uniformly to list, retrieve, update, and delete, and a foreign row it excludes becomes a 404 rather than a 403, so the API does not even confirm that the row exists.

Never authorise by a client-supplied id

The mirror-image mistake is fetching a row by an identifier the client chose and trusting it. A line like Invoice.objects.get(pk=request.data["invoice_id"]) treats a value the caller supplied as if it were proof of entitlement. Always re-scope the lookup by the authenticated user, as in get_object_or_404(Invoice, pk=pk, owner=request.user), so an id that is not theirs simply misses. This one class of bug, trusting a client-chosen identifier, is behind a large share of real data leaks, and it survives review because the line looks utterly ordinary.


Real World Example: An Invoice API That Scopes Every Request

Here is a small invoice API reduced to a single dispatcher. Every request is authenticated first, the queryset is scoped to the caller, ownership decides what a detail fetch returns, and a new invoice takes its owner from the authenticated user rather than from anything the client sent. Two users share the table, and the sequence of calls exercises listing, a legitimate detail read, a cross-owner detail read, an anonymous request, and a create.

INVOICES = [
    {"id": 4711, "owner_id": 1, "amount": 1500},
    {"id": 4712, "owner_id": 2, "amount": 900},
    {"id": 4713, "owner_id": 1, "amount": 400},
]
NEXT_ID = 4714

def scoped(user):
    return [i for i in INVOICES if i["owner_id"] == user["id"]]

def handle(user, action, pk=None, amount=None):
    if user is None:
        return "401 unauthenticated"
    rows = scoped(user)
    if action == "list":
        return "200 [" + ",".join(str(i["id"]) for i in rows) + "]"
    if action == "retrieve":
        for i in rows:
            if i["id"] == pk:
                return "200 invoice " + str(pk) + " amount " + str(i["amount"])
        return "404 not found"
    if action == "create":
        global NEXT_ID
        INVOICES.append({"id": NEXT_ID, "owner_id": user["id"], "amount": amount})
        result = "201 created " + str(NEXT_ID)
        NEXT_ID = NEXT_ID + 1
        return result
    return "405 method not allowed"

ada = {"id": 1, "name": "Ada"}
bob = {"id": 2, "name": "Bob"}
CALLS = [
    ("ada list", ada, "list", None, None),
    ("bob list", bob, "list", None, None),
    ("ada own", ada, "retrieve", 4711, None),
    ("ada foreign", ada, "retrieve", 4712, None),
    ("anon list", None, "list", None, None),
    ("ada create", ada, "create", None, 250),
    ("ada list after", ada, "list", None, None),
]
for label, user, action, pk, amount in CALLS:
    print(label.ljust(15) + " " + handle(user, action, pk, amount))

Output:

ada list        200 [4711,4713]
bob list        200 [4712]
ada own         200 invoice 4711 amount 1500
ada foreign     404 not found
anon list       401 unauthenticated
ada create      201 created 4714
ada list after  200 [4711,4713,4714]

Walk the seven lines in order. Ada's list returns only 4711 and 4713 because scoped filtered Bob's 4712 out before the view saw it; Bob's list returns only his 4712. Ada reads her own invoice 4711 and gets its amount back. Ada then asks for 4712, which is Bob's: because her scoped queryset never contained it, the lookup misses and returns 404 not found, not 403 and not Bob's data. The anonymous caller is rejected at the first gate before any row is touched. Finally Ada creates an invoice; it is assigned id 4714 and, crucially, owner_id 1 taken from ada, and her next list now includes it.

The program gets the important things right. Scoping is applied once, in scoped, and every action reads through it, so listing, detail, and the post-create list are all filtered the same way with no per-action special-casing. The owner of a new invoice comes from the authenticated user, never from the request body, so a client cannot create a row it does not own. A foreign id returns 404 rather than 403, so the API declines to confirm that invoice 4712 even exists. And the anonymous request short-circuits before scoped is ever called, so unauthenticated callers never reach the data layer.

The ada create and ada list after pair is worth dwelling on, because it is where scoping earns its keep. A weaker design might scope only the read paths and let create trust a client-supplied owner_id; here the owner is stamped from the session identity, and the very next list proves the new row lands inside Ada's scope automatically. There is no separate rule to keep in sync, because the same owner_id == user["id"] predicate governs both what she can create and what she can later see.

That said, the code has real flaws worth naming. First, scoped re-filters the entire in-memory list on every call; a database-backed version must push filter(owner=request.user) down to an indexed query rather than scanning every row in Python. Second, ownership lives only in the queryset and there is no separate permission class, so any future code path that fetches an invoice without going through scoped (a reporting join, a management command) would bypass ownership entirely, which is exactly why defence in depth keeps the object-level check too. Third, create accepts amount with no validation at all, so a negative or absurd amount sails through; authorisation is enforced but input validation is missing. Fourth, the global NEXT_ID counter is not concurrency-safe, and two simultaneous creates could collide on an id that a real database sequence would hand out atomically. Fifth, the list is unpaginated, so a user with a million invoices dumps all of them in one response.


Common Mistakes

  1. Treating authentication as authorisation. Confirming who the caller is does not decide what they may touch. An endpoint that checks is_authenticated and stops there lets any logged-in user reach every other user's rows.
  1. Protecting a list with only an object-level permission. has_object_permission never runs for list, so an IsOwner class alone still returns everybody's records. Lists are guarded by scoping the queryset, not by the object permission.
  1. Fetching by a client-supplied id without re-scoping. Model.objects.get(pk=request.data["id"]) trusts a value the caller chose. Always constrain the lookup by the authenticated user, so a foreign id misses instead of leaking.
  1. Returning 403 for rows the user should not know exist. A 403 on a foreign object confirms the object is real. Scope the queryset so the row is simply absent and the response is 404, revealing nothing.
  1. Leaving the default permission as AllowAny. DRF's out-of-the-box default is open. Ship with IsAuthenticated as the project-wide default and relax per view, so a new endpoint is closed until someone deliberately opens it.
  1. Rolling your own password storage. Hashing with hashlib.sha256 or storing anything reversible is strictly worse than Django's salted, deliberately slow hashers. Use set_password and check_password and let the framework upgrade algorithms.
  1. Authorising by email domain or hard-coded name. if user.email.endswith("@corp.com") is not an authorisation system; it breaks the moment roles change. Model roles as groups and check membership.
  1. Storing a JWT wherever is convenient. A token in localStorage is readable by any XSS; a token in a cookie reintroduces CSRF. There is no free option, so pick the trade-off deliberately rather than by accident.
  1. Leaving authentication endpoints unthrottled. Login, password reset, and token refresh with no rate limit are credential stuffing with your server volunteering to help. Throttle them harder than the rest of the API.

Best Practices

  • Set a deny-by-default permission. Configure DEFAULT_PERMISSION_CLASSES to IsAuthenticated project-wide, then open individual views deliberately, so a forgotten view fails closed rather than open.
  • Scope every queryset to the request user. Override get_queryset to filter by owner so list, detail, update, and delete are all constrained uniformly and foreign rows return 404.
  • Keep the object-level permission as well. Defence in depth costs one small class; pairing scoping with has_object_permission protects any code path that fetches a row without the scoped queryset.
  • Take server-owned fields from the identity, never the body. Assign owner from request.user on create, and mark it read-only in the serializer, so a client cannot claim someone else's ownership.
  • Use Django's password hashers. Rely on set_password and check_password; never hash credentials yourself, and let the framework transparently upgrade the algorithm over time.
  • Model roles as groups. Check group membership for coarse roles instead of hard-coding names or email domains, so authorisation survives people changing teams.
  • Choose token storage with eyes open. Weigh localStorage against cookies explicitly, knowing one exposes you to XSS token theft and the other to CSRF, and add the matching mitigation.
  • Throttle authentication endpoints. Apply tighter rate limits to login, password reset, and token refresh than to ordinary reads, and log repeated failures for monitoring.

Practice Exercises

  1. Two-gate tracer. Extend the access(user, obj) function from the Syntax section with a third user who is authenticated and owns a different object. Run all four callers against invoice 4711 and confirm you get exactly one 200, two 403s, and one 401, proving authentication and object ownership are independent checks.
  1. Prove the list hole. Using list_unscoped and list_scoped, add a fourth invoice owned by Bob and re-run both for Ada. Show that the unscoped list grows while the scoped list does not, then write one sentence explaining why has_object_permission would not have helped.
  1. 404 versus 403. Modify handle so that a foreign detail read can be made to return 403 instead of 404 (by checking ownership after fetching from the full table). Run ada foreign both ways and describe exactly what information the 403 version leaks that the 404 version does not.
  1. Stamp the owner, then break it. Change create to trust a client-supplied owner_id instead of user["id"], then have Ada create an invoice claiming owner_id 2. Show that Bob's list now contains a row Ada planted, and explain in one line why taking the owner from the authenticated identity prevents it.