Если POST-запросы по умолчанию защищены csrf Какова цель использования @method_decorator(csrf_protect) в Django?

Я думаю, что все POST, PUT, DELETE запросы CSRF защищены по умолчанию в DRF, но я видел в некоторых обучающих видео, что они используют @method_decorator(csrf_protect) на некоторых class-based представлениях с POST и DELETE запросами, поэтому я сделал то же самое.

Но теперь я думаю, зачем это делать, если эти запросы по умолчанию защищены от CSRF?

@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.'})

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.

Отключение CSRF характерно для API, так как они обычно не работают с куками. Поэтому, если вы создаете Django-приложение, которое, например, будет обслуживать приложение React или Vue, нередко нужно удалить CsrfViewMiddleware.

Вернуться на верх