Skip to content

Authentication & Permissions

Authentication identifies the user making the request. Permissions dictate whether that user has the right to perform the requested action.

Authentication

Authentication in DRF is handled by classes configured in settings or per-view.

Global Settings:

python
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication', # Requires authtoken app
    ]
}

Per-View configuration:

python
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]
    
    # ...

Permissions

Permissions are checked before any logic in your view is run.

Common Built-in Permissions

Permission ClassBehavior
AllowAnyUnrestricted access, regardless of authentication.
IsAuthenticatedDenies access to unauthenticated users.
IsAdminUserDenies access to any user where is_staff=False.
IsAuthenticatedOrReadOnlyAuthenticated users have full access; unauthenticated users have read-only (GET, HEAD, OPTIONS) access.

Custom Permissions

To implement a custom permission, subclass BasePermission and override has_permission and/or has_object_permission.

python
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """
    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the snippet.
        return obj.owner == request.user