37 14 | I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem. I have an application which has authentication and some functionality. I added a new app to it, which uses Django Rest Framework. I want to use the library only in this app. Also I want to make POST request, and I always receive this response: { "detail": "CSRF Failed: CSRF token missing or incorrect."} I have the following code: # urls.pyfrom django.conf.urls import patterns, urlurlpatterns = 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}) I want add the API without affecting the current application. So my questions is how can I disable CSRF only for this app ? | ||||||||||||
|
6 Answers
71accepted | Why this error is happening? This is happening because of the default When you don't define any 'DEFAULT_AUTHENTICATION_CLASSES'= ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication'), Since DRF needs to support both session and non-session based authentication to the same views, it enforces CSRF check for only authenticated users. This means that only authenticated requests require CSRF tokens and anonymous requests may be sent without CSRF tokens. If you're using an AJAX style API with SessionAuthentication, you'll need to include a valid CSRF token for any "unsafe" HTTP method calls, such as What to do then? Now to disable csrf check, you can create a custom authentication class from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return # To not perform the csrf check previously happening In your view, then you can define the authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication) This should handle the csrf error. | ||||||||||||||||
|