Session Auth in Django-Rest-Framwork, Is this really what I have to do to make is CSRF safe?

First off, this code works, it just doesn't feel as clean as it should be for something so simple.

Background: I'm trying to make a custom login API endpoint in DRF that will be consumed by the React Frontend. It seems you have to manually force a csrf to be sent in DRF so that's what I have done.

I didn't want to send over a Django Form because it didn't seem RESTful, but this is the only method I could find to avoid that. Please let me know if this is clean code.

Serializers.py

from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model

UserModel = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    def create(self, validated_data):
        user = UserModel.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            email=validated_data['email'],
        )

        return user

    class Meta:
        model = UserModel
        # Tuple of serialized model fields (see link [2])
        fields = ( "id", "username", 'email', "password", )


View.py

from rest_framework import permissions

from django.contrib.auth import get_user_model # If used custom user model
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from .serializers import UserSerializer

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect


class CreateUserView(APIView):
    model = get_user_model()
    permission_classes = [
        permissions.AllowAny # Or anon users can't register
    ]
    serializer_class = UserSerializer

    @method_decorator(ensure_csrf_cookie)
    def get(self, request, format = None):
        return Response(status=status.HTTP_200_OK)

    @method_decorator(csrf_protect)
    def post(self,request, format = None):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


Read more here: https://stackoverflow.com/questions/67013448/session-auth-in-django-rest-framwork-is-this-really-what-i-have-to-do-to-make-i

Content Attribution

This content was originally published by Joseph Gutstadt at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: