Django Rest Framework刪除csrf我知道有關于Django Rest Framework的答案,但我無法找到解決問題的方法。我有一個具有身份驗證和一些功能的應用程序。我添加了一個新的應用程序,它使用Django Rest Framework。我想只在這個應用程序中使用該庫。我也想發出POST請求,我總是收到這個回復:{
"detail": "CSRF Failed: CSRF token missing or incorrect."}我有以下代碼:# urls.pyfrom django.conf.urls import patterns, url
urlpatterns = patterns(
'api.views',
url(r'^object/$', views.Object.as_view()),)# views.pyfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom django.views.decorators.csrf import csrf_exemptclass Object(APIView):
@csrf_exempt
def post(self, request, format=None):
return Response({'received data': request.data})我想添加API而不影響當前的應用程序。所以我的問題是如何才能為此應用禁用CSRF?
3 回答

小唯快跑啊
TA貢獻1863條經驗 獲得超2個贊
為什么會出現這種錯誤?
這是因為SessionAuthentication
DRF使用的默認方案。DRF SessionAuthentication
使用Django的會話框架進行身份驗證,需要檢查CSRF。
如果未authentication_classes
在視圖/視圖集中定義任何內容,DRF將使用此身份驗證類作為默認值。
'DEFAULT_AUTHENTICATION_CLASSES'= ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication'),
由于DRF需要同時支持對相同視圖的會話和非會話身份驗證,因此它僅對經過身份驗證的用戶執行CSRF檢查。這意味著只有經過身份驗證的請求才需要CSRF令牌,并且可以在沒有CSRF令牌的情況下發送匿名請求。
如果您使用帶有SessionAuthentication的AJAX樣式API,則需要為任何“不安全”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錯誤。
添加回答
舉報
0/150
提交
取消