← Back to Django, page 2

django-0030 · Medium mid

How do authentication and permissions work in Django REST Framework?

Authentication identifies the caller: DRF tries each class in authentication_classes (session, token, JWT via a package) and sets request.user and request.auth. Permissions then decide access: has_permission() runs for every request and has_object_permission() runs when get_object() is called. Failed authentication gives 401 (or 403 for schemes without a WWW-Authenticate header) and failed permission gives 403.

Full answer

DRF separates three checks that run in APIView.initial() before your handler:

  1. Authentication: who is calling?
  2. Permissions: may they do this?
  3. Throttling: are they calling too often?

Authentication classes (set globally in REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] or per view):

  • SessionAuthentication: uses the Django session cookie; enforces CSRF for unsafe methods. Good for a browser front end on the same site.
  • TokenAuthentication: Authorization: Token <key>, keys stored in the authtoken table.
  • BasicAuthentication: mainly for testing.
  • JWT through djangorestframework-simplejwt: Authorization: Bearer <token>, no database lookup per request for the token itself.

Each class returns (user, auth) or None to let the next class try. If none succeed, request.user is AnonymousUser.

Permission classes:

  • AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, DjangoModelPermissions.
  • Combine with &, |, ~.
  • Custom classes implement has_permission(request, view) and/or has_object_permission(request, view, obj).

Object permissions run only when the view calls get_object() (retrieve, update, destroy). They do not filter list results. For lists, filter the queryset in get_queryset().

Status codes: unauthenticated requests get 401 when the first authentication class provides a WWW-Authenticate header (Token, Basic), otherwise 403. Authenticated users without permission get 403.

Set secure defaults globally (IsAuthenticated) and open specific endpoints with AllowAny, rather than the reverse.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "rest_framework.authtoken", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.db import models, connection
from django.urls import path
from rest_framework import generics, permissions, serializers
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
call_command("migrate", verbosity=0)
User = get_user_model()


class Note(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Note)


class IsOwner(permissions.BasePermission):
    message = "You can only open your own notes."

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


class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = ["id", "text"]


class NoteDetail(generics.RetrieveAPIView):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwner]


urlpatterns = [path("notes/<int:pk>/", NoteDetail.as_view())]
settings.ROOT_URLCONF = __name__

kavya = User.objects.create_user("kavya", password="x")
arun = User.objects.create_user("arun", password="x")
note = Note.objects.create(owner=kavya, text="Physics lab on Friday")

c = APIClient()
r = c.get(f"/notes/{note.pk}/")
print("no token:", r.status_code, r.headers.get("WWW-Authenticate"))

c.credentials(HTTP_AUTHORIZATION="Token " + Token.objects.create(user=arun).key)
print("other user:", c.get(f"/notes/{note.pk}/").status_code)

c.credentials(HTTP_AUTHORIZATION="Token " + Token.objects.create(user=kavya).key)
print("owner:", c.get(f"/notes/{note.pk}/").json())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework` (run here with DRF 3.16+). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): no token: 401 Token other user: 403 owner: {'id': 1, 'text': 'Physics lab on Friday'}

Key points

  • Authentication sets request.user; permissions decide access
  • Classes are tried in order; None means try the next
  • Object permissions run only via get_object()
  • Filter list endpoints in get_queryset()
  • Default to IsAuthenticated globally

Common mistakes

  • Relying on has_object_permission to protect list endpoints
  • Setting AllowAny as the global default
  • Mixing up 401 and 403
  • Using SessionAuthentication from a separate front-end domain and fighting CSRF instead of using tokens

Follow-ups

  • How would you let admins read every note but users only their own?
  • How do JWT access and refresh tokens work with simplejwt?
  • Where does throttling fit in the request cycle?

Tips

  • Separate authentication and authorisation clearly
  • Point out that object permissions do not filter lists
  • Explain when a 401 becomes a 403