小编典典

Django Rest Framework移除CSRF

django

我知道有关于Django Rest Framework的答案,但找不到我的问题的解决方案。

我有一个具有身份验证和某些功能的应用程序。我向其中添加了一个新应用,该应用使用Django Rest Framework。我只想在此应用程序中使用库。我也想发出POST请求,并且总是收到以下响应:

{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

我有以下代码:

# urls.py
from django.conf.urls import patterns, url


urlpatterns = patterns(
    'api.views',
    url(r'^object/$', views.Object.as_view()),
)

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt


class Object(APIView):

    @csrf_exempt
    def post(self, request, format=None):
        return Response({'received data': request.data})

我想添加API而不影响当前的应用程序。因此,我的问题是如何仅对此应用程序禁用CSRF?


阅读 1009

收藏
2020-03-25

共1个答案

小编典典

为什么会发生此错误?

发生这种情况是由于SessionAuthenticationDRF使用默认方案。DRF SessionAuthentication使用Django的会话框架进行身份验证,该框架要求检查CSRF。

当你authentication_classes在视图/视图集中未定义任何对象时,DRF将此身份验证类用作默认身份验证类。

'DEFAULT_AUTHENTICATION_CLASSES'= (
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication'
),

由于DRF需要对同一视图同时支持基于会话和基于非会话的身份验证,因此DRF仅对经过身份验证的用户强制执行CSRF检查。这意味着只有经过身份验证的请求才需要CSRF令牌,并且匿名请求可以在没有CSRF令牌的情况下发送。

如果你将AJAX样式的API与SessionAuthentication一起使用,则需要为任何“不安全的” HTTP方法调用(例如PUT, PATCH, POST or DELETE请求)包括有效的CSRF令牌。

那该怎么办呢?

现在要禁用csrf检查,你可以创建CsrfExemptSessionAuthentication从默认SessionAuthentication类扩展的自定义身份验证类。在此身份验证类中,我们将覆盖enforce_csrf()在实际内部进行的检查SessionAuthentication

from rest_framework.authentication import SessionAuthentication, BasicAuthentication 

class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening

在你看来,然后可以将定义authentication_classes为:

authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

这应该处理csrf错误。

2020-03-25