Skip to content Skip to sidebar Skip to footer

Csrf Exempt Failure - Apiview Csrf Django Rest Framework

I have the following code: The problem is when I try to access user-login/ I get an error: 'CSRF Failed: CSRF cookie not set.' What can I do? I am using the django rest framework.

Solution 1:

I assume you use the django rest framework SessionBackend. This backend does a implicit CSRF check

You can avoid this by:

from rest_framework.authentication import SessionAuthentication

classUnsafeSessionAuthentication(SessionAuthentication):

    defauthenticate(self, request):
        http_request = request._request
        user = getattr(http_request, 'user', None)

        ifnot user ornot user.is_active:
           returnNonereturn (user, None)

And set this as authentication_classes in your View

classUnsafeLogin(APIView):
    permission_classes = (AllowAny,) #maybe not needed in your case
    authentication_classes = (UnsafeSessionAuthentication,)

    defpost(self, request, *args, **kwargs):

        username = request.DATA.get("u");
        password = request.DATA.get("p");

        user = authenticate(username=username, password=password)
        if user isnotNone:
           login(request, user)

        return redirect("/")

Solution 2:

Actually, better way to disable csrf check inside SessionAuthentication is:

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication

classSessionAuthentication(OriginalSessionAuthentication):
    defenforce_csrf(self, request):
        return

Solution 3:

The easiest way to solve this problem:

For that there are two ways of authentication in drf see drf auth

BasicAuthentication

SessionAuthentication (default)

SessionAuthentication has a forced csrf check, but BasicAuthentication doesn't. So my way is using BasicAuthentication in my view instead of SessionAuthentication.

from rest_framework.authentication import BasicAuthentication

classUserLogin(generics.CreateAPIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = UserSerializer
    authentication_classes = (BasicAuthentication,)

    defpost(self, request, *args, **kwargs):
        return Response({})

Solution 4:

Probably better to just make the enforce_csrf check do nothing:

from rest_framework.authentication import SessionAuthentication

classUnsafeSessionAuthentication(SessionAuthentication):

    defenforce_csrf(self, *args, **kwargs):
        '''
        Bypass the CSRF checks altogether
        '''pass

Otherwise you'll possibly end up with issues in the future if the upstream authenticate() method changes. Also, it's MUCH simpler to just make the check not do anything :-)

Post a Comment for "Csrf Exempt Failure - Apiview Csrf Django Rest Framework"