[Solved]-CSRF is only checked when authenticated in DRF?


Django REST Framework is disabling CSRF token requirement when using SessionAuthentication and user is not authenticated. This is by design to not mess up other authentication method that don’t require CSRF authentication (because they’re not based on cookies) and you should ensure by yourself that CSRF is validated on login request and it is mentioned in last paragraph of SessionAuthentication documentation. It is advised to either use non-API login process or ensure that API-based login process is fully protected.

You can check how DRFs SessionAuthentication is enforcing CSRF validation when you are logged in and base your view on that.


You can create a child class of APIView that forces CSRF.

from rest_framework import views

class ForceCRSFAPIView(views.APIView):
    def as_view(cls, **initkwargs):
        # Force enables CSRF protection.  This is needed for unauthenticated API endpoints
        # because DjangoRestFramework relies on SessionAuthentication for CSRF validation
        view = super().as_view(**initkwargs)
        view.csrf_exempt = False
        return view

Then all you need to do is change your login view to descend from this

class Login(ForceCRSFAPIView)
    # ...

Leave a comment