Nexus Void Research

Django, Django REST Framework, DRF, Python, API Security, Permissions, Throttling, How-to

How to Secure a Django REST API (DRF Settings and Code)

How to secure a Django REST Framework API: IsAuthenticated by default, scoped querysets, explicit serializer fields, throttling and check --deploy.

To secure a Django REST Framework (DRF) API, change the default permission from AllowAny to IsAuthenticated, filter every queryset by the requesting user, add object-level permissions, list serializer fields explicitly instead of __all__, turn on throttling and pagination limits, and run python manage.py check --deploy with DEBUG = False, a secret key from the environment and strict ALLOWED_HOSTS.

Django ships with strong defaults for web pages: CSRF protection, auto-escaping templates and an ORM that parameterises queries. Django REST Framework is just as capable, but one of its defaults surprises many teams: unless you change it, every view allows any request, logged in or not. This guide covers the settings and patterns that matter for DRF APIs, mapped to the OWASP API Security Top 10.

Step 1: Change the default permission

DRF's default permission class is AllowAny. Set a safe default in settings.py:

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
}
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
}
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
}

Now every view requires login unless it explicitly opts out with permission_classes = [AllowAny], which makes public endpoints easy to find in review.

Step 2: Filter querysets by the user

The most common DRF data leak is a viewset that returns every object:

# Vulnerable: any logged-in user can list and retrieve every invoice
class InvoiceViewSet(viewsets.ModelViewSet):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
# Vulnerable: any logged-in user can list and retrieve every invoice
class InvoiceViewSet(viewsets.ModelViewSet):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
# Vulnerable: any logged-in user can list and retrieve every invoice
class InvoiceViewSet(viewsets.ModelViewSet):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer

Scope it to the caller:

class InvoiceViewSet(viewsets.ModelViewSet):
    serializer_class = InvoiceSerializer

    def get_queryset(self):
        return Invoice.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
class InvoiceViewSet(viewsets.ModelViewSet):
    serializer_class = InvoiceSerializer

    def get_queryset(self):
        return Invoice.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
class InvoiceViewSet(viewsets.ModelViewSet):
    serializer_class = InvoiceSerializer

    def get_queryset(self):
        return Invoice.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

Because retrieve, update and delete all start from get_queryset(), another user's IDs simply return 404. This is the DRF fix for IDOR, OWASP's number one API risk. MITRE tracks the underlying weakness as CWE-639.

Step 3: Add object-level permissions where needed

When access depends on more than ownership, such as team roles, write a permission class:

class IsTeamEditor(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return obj.team.members.filter(id=request.user.id).exists()
        return obj.team.editors.filter(id=request.user.id).exists()
class IsTeamEditor(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return obj.team.members.filter(id=request.user.id).exists()
        return obj.team.editors.filter(id=request.user.id).exists()
class IsTeamEditor(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return obj.team.members.filter(id=request.user.id).exists()
        return obj.team.editors.filter(id=request.user.id).exists()

One catch: DRF calls has_object_permission for single-object actions, not for list views. Always filter the queryset as well, or the list endpoint will still return objects the user cannot open.

Step 4: List serializer fields explicitly

fields = "__all__" exposes every model field, including ones you add later, and makes them writable unless marked otherwise:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["id", "display_name", "timezone", "plan"]
        read_only_fields = ["id", "plan"]
class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["id", "display_name", "timezone", "plan"]
        read_only_fields = ["id", "plan"]
class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["id", "display_name", "timezone", "plan"]
        read_only_fields = ["id", "plan"]

Explicit fields stop users reading internal data and stop them writing fields like is_staff, plan or owner (mass assignment). Use separate serializers for admin views if admins need more.

Step 5: Throttle and paginate

REST_FRAMEWORK = {
    # ...
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {"anon": "30/minute", "user": "300/minute"},
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 25,
}
REST_FRAMEWORK = {
    # ...
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {"anon": "30/minute", "user": "300/minute"},
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 25,
}
REST_FRAMEWORK = {
    # ...
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {"anon": "30/minute", "user": "300/minute"},
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 25,
}

Use ScopedRateThrottle for tighter limits on login, password reset and expensive endpoints, and set max_page_size on custom paginators so clients cannot request a million rows. Throttling in DRF relies on your cache, so configure a shared cache such as Redis in production.

Step 6: Lock down production settings

Run Django's deployment checks:

python manage.py check --deploy
python manage.py check --deploy
python manage.py check --deploy

and fix what it reports. The essentials:

DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["api.example.com"]

SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")  # only behind a trusted proxy
DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["api.example.com"]

SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")  # only behind a trusted proxy
DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["api.example.com"]

SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")  # only behind a trusted proxy

DEBUG = True in production leaks settings, SQL and stack traces on every error. Keep the secret key out of the repository; see how to store API keys securely.

Step 7: Configure CORS, CSRF and renderers

  • CORS: with django-cors-headers, list exact origins in CORS_ALLOWED_ORIGINS; never combine CORS_ALLOW_ALL_ORIGINS = True with credentials.

  • CSRF: SessionAuthentication enforces CSRF for authenticated unsafe requests; keep it on for browser clients. Token-based clients are not subject to CSRF in the same way.

  • Browsable API: in production, consider limiting renderers to JSON so the HTML browsable API is not exposed:

"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],

Step 8: Keep raw SQL and filters safe

The ORM parameterises queries. Risk comes from raw(), extra(), RawSQL and cursor.execute() with interpolated strings; always pass params. With django-filter and OrderingFilter, declare ordering_fields explicitly so clients cannot sort or filter on sensitive fields. See how to prevent SQL injection.

Step 9: Harden authentication

  • With Simple JWT, keep access tokens short-lived, rotate refresh tokens and blacklist them on logout.

  • Use Django's password validators and its default PBKDF2 or Argon2 hashers.

  • Require MFA for staff and lock down /admin (rename the path, restrict by IP or SSO, and require staff MFA).

Django REST Framework security checklist

Check

Done when

Default permission

IsAuthenticated (or stricter) in settings

Querysets scoped

Every get_queryset filters by user or tenant

Object permissions

Custom permissions for shared data, plus queryset filtering

Explicit serializer fields

No __all__; sensitive fields read-only

Throttling

Anon, user and scoped rates; shared cache

Pagination limits

Page size and max page size set

Deploy check clean

check --deploy passes; DEBUG = False

CORS and renderers

Exact origins; JSON-only renderer in production

Raw SQL safe

All raw queries use params; ordering fields declared

How does ARGUS help secure Django REST APIs?

  1. API inventory lists the HTTP routes your Django code defines and marks each one Authenticated, Open or Not determined, so views that fell back to AllowAny stand out.

  2. AI business logic analysis looks for IDOR, privilege escalation and authentication bypass in Python, such as viewsets that return objects.all() to any user.

  3. Static analysis and taint analysis flag raw(), extra() and cursor.execute() with interpolated input, and dangerous settings, following request data across files.

  4. Dependency scanning reads requirements.txt and Pipfile.lock, ranks Django and DRF CVEs by EPSS, CISA KEV and reachability, and Assign to Agent opens a verified fix pull request for you to review and merge.

Limits: AI passes run when AI scanning is enabled. ARGUS analyses code, not your deployed settings or headers. See ARGUS SAST, or scan a repository free.

Frequently asked questions

How do I secure a Django REST API?

Set DEFAULT_PERMISSION_CLASSES to IsAuthenticated, filter every queryset by the requesting user, add object-level permissions for shared data, list serializer fields explicitly, enable throttling and pagination, and run manage.py check --deploy with DEBUG = False, an environment-provided secret key and strict ALLOWED_HOSTS.

What is the default permission in Django REST Framework?

AllowAny. Unless you set DEFAULT_PERMISSION_CLASSES in your REST_FRAMEWORK settings or on each view, every endpoint accepts requests from anyone, including anonymous users. Changing the default to IsAuthenticated makes public endpoints an explicit, reviewable exception.

How do I restrict a DRF viewset to the user's own objects?

Override get_queryset() to return only the user's objects, for example Invoice.objects.filter(owner=self.request.user), and set the owner in perform_create. Retrieve, update and delete all use that queryset, so other users' objects return 404.

Why is has_object_permission not called on list views?

DRF only calls has_object_permission when a view fetches a single object, such as retrieve, update or delete. List views return many objects at once, so you must filter the queryset to enforce access. Use queryset filtering for lists and object permissions for finer single-object rules.

Is fields = "all" safe in DRF serializers?

It is risky. It exposes every model field, including ones added later, and makes them writable unless marked read-only, which can leak internal data and allow mass assignment of fields such as is_staff or owner. List fields explicitly and mark sensitive ones read-only.

How do I rate limit a Django REST API?

Enable AnonRateThrottle and UserRateThrottle with rates in DEFAULT_THROTTLE_RATES, add ScopedRateThrottle for login and password reset, and back throttling with a shared cache such as Redis in production so limits apply across all workers.

What does python manage.py check --deploy do?

It runs Django's deployment checklist and warns about insecure production settings, such as DEBUG = True, a weak or missing SECRET_KEY, missing HTTPS redirects, HSTS, secure cookie flags and ALLOWED_HOSTS. Fix every warning before going live.

Should I disable the DRF browsable API in production?

For private APIs it is a good idea: set DEFAULT_RENDERER_CLASSES to JSON only so the HTML interface is not exposed. The browsable API respects permissions, but removing it reduces information shown to unauthenticated visitors and avoids surprises.

DATA SOURCES

OWASP API Security Top 10: https://owasp.org/API-Security/ ; CWE-639

Liked this post? Share it: