Removing CSRF Protection in Django Rest Framework

The Django web framework provides great security features out of the box, including protection against cross-site request forgery (CSRF) attacks. However, you may need to disable CSRF protection for API endpoints built with Django Rest Framework. In this post, we’ll examine when and why you might want to remove this protection

What is CSRF and Why is it Important?

First, let’s review whatCSRF is and why it matters. CSRF or XSRF attacks involve tricking the victim into loading a page that contains a malicious request. For example, say a user logs into their bank account then visits an infected page. That page could contain code that secretly makes a request to transfer funds out of the user’s account.

Since the user is already logged in, the bank website processes this forged request as if the user submitted it. So even though the user didn’t intend to transfer the money, the attack succeeds.

To prevent this, Django checks for aCSRF token before accepting POST, PUT, and DELETE requests. This confirms the request came from the user’s browsing session rather than an unauthorized page. As you can see, CSRF protection is vital for securing sites that handle sensitive data or transactions.

When to Remove CSRF Protection in Django Rest Framework

However, CSRF attacks primarily impact browser-based apps and sites. For APIs built strictly for programmatic access, CSRF poses less of a threat.

Additionally, requiringCSRF tokens can make API testing and usage more complicated. The consumer needs tograb a token before making each POST, PUT, or DELETE request.

So for Django Rest Framework API projects, removingCSRF may make development easier without significantly impacting security. As a result, disablingCSRF protection is a common choice for API backends.

How to Remove CSRF Checks in Django Rest Framework

Fortunately, Django Rest Framework makes it simple to disable CSRF. There are just two steps:

1. Add ‘rest_framework.authentication.SessionAuthentication’

Start by adding SessionAuthentication to the authentication classes in your settings.py:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        # Any other authentication classes
    ]
}

This is required because CSRF checks use the django.contrib.auth session cookie for validation. So if you removeCSRF, you need to explicitly enable session auth.

2. Set ‘rest_framework.csrf.CsrfViewMiddleware’ to DISABLED

Next, disable theCSRF middleware by adding this to your settings:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        # Any other authentication classes
    ],

    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],

    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}

And that’s it! Django Rest Framework will now accept POST, PUT, and DELETE requests without CSRF verification.

When to Re-EnableCSRF Protection

DisablingCSRF does come with some risk. If you incorporate browser-based views later, you may open yourself up to potentialCSRF attacks.

So make sure to re-enableCSRF if you switch your API to include:

  • Browser-rendered web pages
  • Forms for data entry
  • POST/PUT/DELETE requests without API tokens

Essentially, any app behavior that relies on cookies and sessions for validation is vulnerable.

You can also whitelist API routes that needCSRF exemptions, leaving it enabled for all other views.

Summary

In summary, removing CSRF protection makes sense for API backends focused on programmatic access. Just take care to re-enable it if you incorporate browseable interfaces later on.

And if you do disableCSRF checks, be sure to explicitly add session authentication first. Following these simple steps will make your Django Rest Framework APIs more smooth and secure.