Introduction
DRF provides multiple authentication classes for securing APIs.
Authentication Classes
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
"rest_framework.authentication.TokenAuthentication",
]
}
Token Authentication
# Install and migrate
# settings.py
INSTALLED_APPS = [
"rest_framework.authtoken",
]
# Create token
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=user)
# Use in request
# Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Permission Classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
class ProtectedView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"message": "Protected content"})
Custom Permission
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
Practice Problems
- Set up token authentication
- Create permission classes
- Secure endpoints
- Implement custom authentication
- Handle unauthorized requests