DRF provides multiple authentication backends for API security.
1from rest_framework.authentication import (2 TokenAuthentication,3 SessionAuthentication,4 BaseAuthentication5)6from rest_framework.permissions import IsAuthenticated78# Token Authentication9class UserViewSet(viewsets.ModelViewSet):10 queryset = User.objects.all()11 serializer_class = UserSerializer12 authentication_classes = [TokenAuthentication]13 permission_classes = [IsAuthenticated]1415# Custom Authentication16class APIKeyAuthentication(BaseAuthentication):17 def authenticate(self, request):18 api_key = request.META.get("HTTP_X_API_KEY")19 if not api_key:20 return None2122 try:23 user = User.objects.get(api_key=api_key)24 except User.DoesNotExist:25 raise AuthenticationFailed("Invalid API key")2627 return (user, api_key)2829# settings.py30REST_FRAMEWORK = {31 "DEFAULT_AUTHENTICATION_CLASSES": [32 "rest_framework.authentication.TokenAuthentication",33 "rest_framework.authentication.SessionAuthentication",34 ],35 "DEFAULT_PERMISSION_CLASSES": [36 "rest_framework.permissions.IsAuthenticated",37 ],38}
Common backends:
TokenAuthentication — simple token.SessionAuthentication — browser sessions.JWTAuthentication — JSON Web Tokens.OAuth2Authentication — OAuth 2.0.