Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Authentication and Permissions

DRF Permission Classes

Control access in Django REST Framework with permission classes: AllowAny, IsAuthenticated, IsAdminUser, combining with and/or/not, per-action rules and DjangoModelPermissions.

Authentication tells DRF who the caller is. Permissions decide whether that caller may do what they are asking. Every view runs its permission classes after authentication and before the handler, so a request that fails a check never reaches your code.

A permission class answers one yes-or-no question. When the answer is no, DRF raises PermissionDenied (status 403) or, when the caller is anonymous and the first authentication class provides a WWW-Authenticate header, NotAuthenticated (status 401). This lesson covers the built-in classes, how to combine them, how to vary them per action and how to let staff manage rules in the admin with model permissions. Rules about individual rows come next, in Custom and Object-Level Permissions.

Where to set permissions

Set a safe project-wide default, then loosen it view by view:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
}
Python
# views.py (read-only)
class PublicStatus(APIView):
    permission_classes = [permissions.AllowAny]   # overrides the default

The built-in default is AllowAny, which means an API with no configuration is open to everyone. Secure by default: make IsAuthenticated the global setting and mark public endpoints explicitly.

If permission_classes lists several classes, all of them must pass.

The built-in classes

Class Passes when
AllowAny always
IsAuthenticated request.user is logged in
IsAdminUser request.user.is_staff is true
IsAuthenticatedOrReadOnly the method is safe (GET, HEAD, OPTIONS), or the user is logged in
DjangoModelPermissions the user holds the model permission matching the method
DjangoModelPermissionsOrAnonReadOnly same, but anonymous reads are allowed
DjangoObjectPermissions per-object permissions (needs a backend such as django-guardian)

The next example runs the same two requests (GET and POST) against four endpoints as three kinds of callers, so you can see the whole matrix. It also defines a tiny custom ReadOnly class and combines it with IsAdminUser using the | operator.

Combining classes: &, |, ~

Classes can be composed into new ones:

  • A & B: both must pass (the same as listing both).
  • A | B: at least one must pass.
  • ~A: passes when A fails.

Operators let you express rules such as "staff may do anything, everyone else may only read" without writing a new class: IsAdminUser | ReadOnly.

Python The permission matrix

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
(GET / POST)             anonymous      member       staff
allow-any                200 / 201   200 / 201   200 / 201
authenticated            403 / 403   200 / 201   200 / 201
admin-only               403 / 403   403 / 403   200 / 201
auth-or-read-only        200 / 403   200 / 201   200 / 201
admin-or-read-only       200 / 403   200 / 403   200 / 201
not-read-only            403 / 201   403 / 201   403 / 201

Read the table row by row. admin-or-read-only is the pattern behind most public catalogs: everyone reads, only staff write. not-read-only shows ~ flipping a class. Anonymous callers get 403 here because the default authentication classes list SessionAuthentication first; with a header-based scheme first they would get 401.

Different permissions per action

A ViewSet bundles several actions (list, retrieve, create, update, partial_update, destroy) in one class, and they often need different rules: anyone may read, members may create, only staff may delete. Override get_permissions() and return instances based on self.action:

Python Per-action permissions in a ViewSet

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
anonymous  {'list': 200, 'create': 403, 'edit': 403, 'delete': 403}
member     {'list': 200, 'create': 201, 'edit': 200, 'delete': 403}
staff      {'list': 200, 'create': 201, 'edit': 200, 'delete': 204}

The member's delete is 403 because IsAdminUser failed. The staff user's delete is 204. (The post with id 2 exists because the member created it a line earlier.) You can also use the @action decorator's own permission_classes=[...] argument for extra routes such as /posts/1/publish/.

Model permissions with DjangoModelPermissions

Django already stores add_x, change_x, delete_x and view_x permissions for every model, and you can give them to users or to groups in the admin site. DjangoModelPermissions reuses them, so non-programmers can change who may do what without a deploy:

HTTP method Required permission
GET, HEAD, OPTIONS none (add a custom class if you need view_x)
POST add_x
PUT, PATCH change_x
DELETE delete_x

The class reads the model from the view's queryset attribute (or get_queryset()), so define it. It also requires a logged-in user for every request.

Python Model permissions granted through a group

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
eve (catalog-editors) | list: 200 | create: 201 | edit: 200 | delete: 403
vic (no permissions) | list: 200 | create: 403 | edit: 403 | delete: 403

Eve may create and edit through her group, but deleting is refused because the group has no delete_product. Vic can read but nothing else. Moving a user between groups changes the API's behaviour immediately, with no code change.

Choosing between the options

  • Everyone reads, staff writes: IsAdminUser | ReadOnly, or IsAuthenticatedOrReadOnly when any member may write.
  • Roles managed by non-developers: DjangoModelPermissions plus groups.
  • "Only the owner may change this row": an object-level permission (next lesson).
  • Different rules per action: get_permissions().

Common mistakes

  • Forgetting that the default is AllowAny. Set DEFAULT_PERMISSION_CLASSES first.
  • Assuming a permission class on the view also filters rows. It does not; it only says yes or no to the request.
  • Using DjangoModelPermissions on a view without a queryset. DRF raises an error because it cannot find the model.
  • Testing only as a superuser. Superusers pass model-permission checks automatically, so always test with a plain member too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is DRF's default permission class if you configure nothing?

    An unconfigured API is open to everyone, so set DEFAULT_PERMISSION_CLASSES to something stricter.
  2. 2. What does permission_classes = [IsAuthenticated, IsAdminUser] require?

    All classes in the list must pass. Use IsAuthenticated | IsAdminUser if either should be enough (although IsAdminUser alone already implies a logged-in staff user).
  3. 3. How do you give list and retrieve to everyone but restrict destroy to staff in one ViewSet?

    get_permissions() runs for each request, and self.action holds the current action name.
  4. 4. Which HTTP method needs the add_<model> permission under DjangoModelPermissions?

    POST maps to add, PUT and PATCH to change, DELETE to delete. GET needs no permission by default.

Summary

  • Permissions run after authentication and before the view; every class in the list must pass.
  • Secure by default: set IsAuthenticated globally and open endpoints explicitly with AllowAny.
  • Combine classes with &, | and ~; vary rules per action in get_permissions().
  • DjangoModelPermissions lets staff manage access through groups in the admin.
  • Row-level rules need object permissions or a filtered queryset.

Next: Custom and Object-Level Permissions