V
V
Vladimir Kuts2017-11-15 17:02:35
Django
Vladimir Kuts, 2017-11-15 17:02:35

Disable CSRF for a single POST request?

There is a certain API request that a third-party site makes a request with some parameters, and after that I need to redirect to a specific page of my site.

from rest_framework.generics import GenericAPIView
from serializers import AddSomethingSerializer

class AddingSomething(GenericAPIView):
    permission_classes = (permissions.AllowAny, )
    serializer_class = AddSomethingSerializer
    queryset = None

    def post(self, request, **kwargs):
         # .. Some magic ..
         return HttpResponseRedirect(redirect_to=reverse('something_added'))

Everything is fine, but when redirecting from a third-party site, an exception occurs:
"detail": "CSRF Failed: CSRF token missing or incorrect."

How can I disable CSRF validation only for this API, but leave it on for other APIs?
Tried
@method_decorator(csrf_exempt)
def post(self, request, **kwargs)

- did not help
@method_decorator(csrf_exempt, name='dispatch')
class AddingSomething(GenericAPIView):

- did not help
from django.views.decorators.csrf import csrf_exempt
from views import AddingSomething

urlpatterns = [
    url('^add_something/$', csrf_exempt(AddingSomething.as_view()), name='api-add-something'),
    ...

- did not help
Option to disable completely in authentication_classes - not suitable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Bragin, 2017-11-15
@fox_12

Drf, when using SessionAuthentication, forces a check for a valid CSRF token for insecure request methods. csrf_exempt decorators will not work with SessionAuthentication.
The solution option, in principle, has already been thrown off to you with links to SO.

from rest_framework.authentication import SessionAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return None


class AddingSomething(GenericAPIView):
    permission_classes = (permissions.AllowAny, )
    serializer_class = AddSomethingSerializer
    authentication_classes = (CsrfExemptSessionAuthentication,)
    queryset = None

    def post(self, request, **kwargs):
         # .. Some magic ..
         return HttpResponseRedirect(redirect_to=reverse('something_added'))

A
Alexander, 2017-11-15
@kentuck1213

Try https://stackoverflow.com/questions/16458166/how-t...
https://stackoverflow.com/questions/30871033/djang...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question