Koki's personal blog

Koki's personal blog

Another fine, responsive site template by HTML5 UP.

CSRF Token Authentication in Django REST framework

A guide on how to implement CSRF token authentication in Web APIs using Django REST framework.

Koki

3-Minute Read

This article explains how to implement CSRF token authentication in Web APIs using Django REST framework..

The following lists are the table of contents about this article.

Target Audience

  • Those developing REST APIs using Django REST framework.
  • Individuals interested in mechanisms to prevent data tampering.
  • Those with basic knowledge of CSRF token authentication.

Environment

Here is the environment in which the author confirmed the operation:

  • Python 3.11
  • Django 4.2.2
  • Django REST framework 3.14.0

Prerequisites

  • Django and Django REST framework should be installed.
  • A Django project should already be set up.
  • Familiarity with the basic concepts of REST APIs.

How to Implement CSRF Token Authentication

Why Implement CSRF Token Authentication?

Even in REST API development, there may be a need to introduce mechanisms to prevent tampering of form submission data.
By implementing CSRF token authentication, you can include the CSRF token in the header when sending requests such as POST, PUT, PATCH, and DELETE to the server.
This allows you to verify and detect/block tampered form submission data.
However, note that this goes against the best practices of REST APIs, which prohibit maintaining state.

Implementing an API to Return CSRF Tokens

First, we need to implement an API that issues and returns a CSRF token.
Implement the following code in the file where you’re building your Web API, and register it in urls.py to make it externally accessible.
In this case, we’ll create an apis.py file under the directory where models.py and views.py are located.

from typing import Self
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

class CSRFTokens(APIView):
    def get(self: Self, request: Request) -> Response:
        return Response({"token": get_token(request)})

Creating the Authentication Class

Next, we’ll implement the code for CSRF token authentication.
Create an authentications.py file under the directory where models.py and views.py are located and add the following code.

from rest_framework.authentication import SessionAuthentication

class CSRFOnlySessionAuthentication(SessionAuthentication):
    def authenticate(self, request):
        self.enforce_csrf(request)
        return None

Setting APIView

Then, setting the authentication class you’ve created in your APIView. Below is a sample code:

from rest_framework.views import APIView
from .authentications import CSRFOnlySessionAuthentication

class SampleResources(APIView):
    authentication_classes = [CSRFOnlySessionAuthentication]

    # Other methods such as  get or post

Points to Note for Testing

When testing this authentication method in test code, if you don’t pass enforce_csrf_checks=True when initializing the APIClient, CSRF token authentication will be ignored. If you’re testing for the presence or verification of the CSRF token, always initialize the APIClient with the parameter enforce_csrf_checks=True as shown below:

from rest_framework.test import APIClient

client = APIClient(enforce_csrf_checks=True)

Recent Posts

Categories