Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Authentication and Permissions

Custom and Object-Level Permissions in DRF

Write your own Django REST Framework permission classes: has_permission versus has_object_permission, owner checks, scoped querysets, group roles, IP allow lists and custom error messages.

The built-in permission classes answer broad questions: is the caller logged in, are they staff? Real applications ask narrower ones. Is this note yours? Is the caller a moderator? Is the request coming from the office network? For those you write a custom permission class.

A custom class is a subclass of BasePermission with up to two methods, and the difference between them is the most important idea in this lesson.

Method Called Typical question
has_permission(request, view) for every request, before the handler "May this caller use this endpoint at all?"
has_object_permission(request, view, obj) only when self.get_object() (or check_object_permissions()) runs "May this caller touch this row?"

Both default to True. Returning False produces a 403 (or 401 for anonymous callers with a header-based scheme), using the class's message attribute as the error detail.

has_object_permission is not a filter

Object permissions are checked in get_object(), so they protect retrieve, update, partial_update and destroy. The list action never calls get_object(): DRF does not run the check for each row of a list. If a rule is really about visibility, filter the queryset in get_queryset() instead.

The example puts the two approaches side by side. /open-notes/ uses only an object permission, /private-notes/ also scopes its queryset. Watch both the detail request for someone else's note and the list.

Python Object permission versus a scoped queryset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
open-notes     Sam's note: 403 {'detail': 'You do not own this note.'} | rows in list: 2
private-notes  Sam's note: 404 {'detail': 'No Note matches the given query.'} | rows in list: 1

With only the object permission, Mia gets a clear 403 for Sam's note, but the list still returned two rows, so she can read Sam's text there. The scoped queryset hides the row completely: 404, and the list shows only her own. For private data, scope the queryset; keep the object permission as a second line of defence (and for rules about writing rather than seeing).

Role-based permissions and composition

A permission that depends on the user rather than the object belongs in has_permission(). Here is a small factory that builds a "member of this group" permission, which you can then combine with the | operator:

IsOwner | InGroup("moderators") means "the owner, or any moderator." When DRF combines classes with | it evaluates each class's has_permission and then, for objects, has_object_permission, and passes if either side passes both.

Python Owner or moderator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
sam (stranger)   DELETE /notes/1/ -> 403 {'detail': 'You do not have permission to perform this action.'}
mia (owner)      DELETE /notes/1/ -> 204 
mo (moderator)   DELETE /notes/1/ -> 404 {'detail': 'No Note matches the given query.'}

Each denial returns the message of the permission that failed. When two classes are combined with |, DRF reports the message of the last class tried. If you want one clear sentence, set message on a small wrapper class instead.

Request-level rules and manual object checks

has_permission() can look at anything on the request: an IP address, a header, the time of day, a feature flag. The next example defines an IP allow list, and also shows how to check object permissions yourself in a plain APIView, where DRF has no get_object() to call them for you. Remember: get_object_or_404() does not run object permissions, you must call self.check_object_permissions(request, obj) explicitly.

Python IP allow list and a manual object check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
from the internet: 403 {'detail': 'This endpoint is only available from the office network.'}
from the office, owner: 200 {'id': 1, 'title': 'Budget 2026'}
from the office, stranger: 403 {'detail': 'Only the owner may open this document.'}
missing document: 404

Behind a proxy or load balancer, REMOTE_ADDR is the proxy's address, not the visitor's. A real allow list must read the forwarded header your infrastructure sets (and only trust it when it comes from your own proxy), otherwise anyone could spoof it.

Writing good permission classes

  • Keep them small and single-purpose. IsOwner, IsModerator, ReadOnly. Combine them with &, | and ~.
  • Set message. A clear sentence helps API users more than the default "You do not have permission to perform this action."
  • Do not hit the database in has_permission when you can avoid it. It runs on every request. Cache group names on the user object or in the token claims if it matters.
  • Never rely on the client. Set owners in perform_create() from request.user, never from request data.
  • Test the denials. A permission that is never tested as a non-owner proves nothing. See Testing authentication and permissions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method of a permission class runs for every request, including list requests?

    has_permission() runs before the handler on every request. has_object_permission() only runs when get_object() or check_object_permissions() is called.
  2. 2. How do you keep other users' notes out of a list response?

    List actions do not run object permissions. Scope the queryset, which also turns access to a foreign row into a 404.
  3. 3. In a plain APIView, what must you call so that has_object_permission() runs for an object you fetched yourself?

    get_object_or_404() only fetches the row. check_object_permissions() runs every permission's has_object_permission().
  4. 4. What does permission_classes = [IsOwner | InGroup('moderators')] allow?

    The | operator passes when at least one side passes.

Summary

  • Subclass BasePermission; use has_permission() for request-level rules and has_object_permission() for row-level rules.
  • Object permissions do not apply to list responses: scope the queryset for private data.
  • Build small classes (owner, role, IP) and combine them with &, | and ~.
  • In an APIView, call check_object_permissions() yourself.
  • Set clear message values and always test the denied cases.

Next: Filtering with django-filter