Django REST Framework: Authentication, Permissions & Filtering
Authentication
# Per-view authentication override
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
class ArticleView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
# Token authentication setup
# INSTALLED_APPS: add 'rest_framework.authtoken'
# python manage.py migrate
# Generate token
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=user)
# Client sends: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4
# JWT (recommended for production)
# pip install djangorestframework-simplejwt
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('auth/token/', TokenObtainPairView.as_view()),
path('auth/token/refresh/', TokenRefreshView.as_view()),
]
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
# Client sends: Authorization: Bearer <access_token>
# Session authentication (for browser-based APIs / browsable API)
# Already included in defaults — works with Django loginPermissions
from rest_framework.permissions import BasePermission, IsAuthenticated, IsAdminUser, AllowAny
# Custom permission
class IsAuthorOrReadOnly(BasePermission):
def has_permission(self, request, view):
# Allow read for anyone
if request.method in ('GET', 'HEAD', 'OPTIONS'):
return True
return request.user.is_authenticated
def has_object_permission(self, request, view, obj):
# Read allowed for all authenticated
if request.method in ('GET', 'HEAD', 'OPTIONS'):
return True
# Write only if owner
return obj.author == request.user
class ArticleView(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsAuthenticated, IsAuthorOrReadOnly]
# Common built-in permissions:
# AllowAny — no restriction
# IsAuthenticated — must be logged in
# IsAdminUser — staff only
# IsAuthenticatedOrReadOnly — read for all, write requires authFiltering, Search & Ordering
pip install django-filter# settings.py
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
],
}
class ArticleListView(generics.ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filterset_fields = ['author', 'status'] # ?author=1&status=published
search_fields = ['title', 'content'] # ?search=keyword (icontains)
ordering_fields = ['created_at', 'title'] # ?ordering=-created_at
ordering = ['-created_at'] # default ordering
# Custom FilterSet
import django_filters
class ArticleFilter(django_filters.FilterSet):
created_after = django_filters.DateFilter(field_name='created_at', lookup_expr='gte')
title = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Article
fields = ['author', 'status', 'title', 'created_after']
class ArticleListView(generics.ListAPIView):
filterset_class = ArticleFilterKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free