Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you implement authentication and permissions in Django REST Framework? Django REST Framework में authentication और permissions कैसे implement करते हैं?

Answer

Authentication identifies who the user is (TokenAuthentication, JWTAuthentication, SessionAuthentication). Permissions determine what authenticated users can do (IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly). Apply at view, viewset, or global level.

// settings.py - Global configuration
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

// Token Authentication Setup
# Add to INSTALLED_APPS
INSTALLED_APPS = [
    'rest_framework.authtoken',
    'myapp',
]

# Create token for user
python manage.py drf_create_token username

# Client sends token in header
# curl -H 'Authorization: Token abc123def456' http://localhost:8000/api/books/

// Built-in Permission Classes
from rest_framework.permissions import (
    IsAuthenticated,
    IsAdminUser,
    IsAuthenticatedOrReadOnly,
    AllowAny,
)

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    # Only authenticated users can access
    permission_classes = [IsAuthenticated]

// Different permissions for different actions
class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    
    def get_permissions(self):
        if self.action == 'list' or self.action == 'retrieve':
            # Anyone can view
            permission_classes = [AllowAny]
        elif self.action == 'create':
            # Only authenticated users can create
            permission_classes = [IsAuthenticated]
        else:
            # Only admins can update/delete
            permission_classes = [IsAdminUser]
        
        return [permission() for permission in permission_classes]

// Custom Permissions
from rest_framework.permissions import BasePermission

class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        # Allow GET requests for anyone
        if request.method in ['GET', 'HEAD', 'OPTIONS']:
            return True
        # Only allow edits by the book's author
        return obj.author == request.user

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = [IsOwnerOrReadOnly]

// JWT Authentication (Token with expiry)
pip install djangorestframework-simplejwt

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework_simplejwt.authentication import JWTAuthentication

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

# urls.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

# Client usage:
# 1. POST /api/token/ with username/password -> get access + refresh tokens
# 2. Use access token in Authorization header
# 3. When access expires, POST /api/token/refresh/ with refresh token

// APIView-level permissions
from rest_framework.decorators import api_view, permission_classes

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def book_list(request):
    # Only authenticated users can access
    pass

Authentication user को identify करता है (Token, JWT, Session)। Permissions decide करते हैं कि user क्या कर सकता है।

Was this answer clear?