Search code examples
pythondjangodjango-rest-frameworkdjango-views

If POST requests are csrf protected by default What is the purpose of using @method_decorator(csrf_protect) in Django?


I think all POST, PUT, DELETE requests is CSRF protected by default in DRF, But I saw in some tutorial videos that they are using @method_decorator(csrf_protect) on some class-based views with POST and DELETE requests, so I did it same.

But now I'm thinking what is the purpose of doing that when these requests are CSRF protected by default?

@method_decorator(csrf_protect, name='dispatch')
class LogoutView(APIView):
    def post(self, request, format=None):
        try:
            auth.logout(request)
            return Response({'success': 'Logged out.'})
        except Exception as e:
            print(e)
        return Response({'error': 'Something went wrong.'})

Solution

  • POST requests are normally protected for CSRF forgery, yes. But that is not by Django itself, but by the CsrfViewMiddleware [Django-doc]. This middleware thus should be in the MIDDLEWARE setting [Django-doc], and by default, it is. But you can remove the middleware, for example if you don't want to protect this by default. In that case you can use the @csrf_protect decorator [Django-doc] to do this only on a certain set of view(s).

    In other words, you can choose to add the CsrfViewMiddleware to the MIDDLEWARE setting (and for a fresh Django project, it is), and then all views are by default CSRF protected, unless you specify this with the @csrf_exempt decorator [Django-doc], or you can remove the middleware, and only mark certain views a CSRF protected.

    Disabling CSRF is common for APIs, since these usually don't work with cookies. So if you make a Django application that for example will serve a React or Vue app, it is not uncommon to remove the CsrfViewMiddleware.