Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set django.contrib.auth.views.login as csrf_exempt

I'm developing a just-for-learn iOS app who interacts with my Django application.

I'm at login part: my client fails to login into Django app due to csrf protection.

For the others views I just would add csrf_exempt decorator for disable it, but for built-in django.contrib.auth.views.login ?

like image 904
Fred Collins Avatar asked Oct 29 '25 17:10

Fred Collins


1 Answers

In modern Django (last tested on 1.11), one way to disable the CSRF check is to subclass the LoginView and override its dispatch method, which is explicitly decorated with csrf_protect (as seen here).

The resulting CBV is along the lines of:

from django.contrib.auth.views import LoginView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect


class DangerousLoginView(LoginView):
    '''A LoginView with no CSRF protection.'''

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        if self.redirect_authenticated_user and self.request.user.is_authenticated:
            redirect_to = self.get_success_url()
            return HttpResponseRedirect(redirect_to)
        return super(LoginView, self).dispatch(request, *args, **kwargs)

See the entire urls.py file here.

The idea is to replicate the exact same method, while replacing csrf_protect with csrf_exempt. There might be a cleaner way to do this, for example, using undecorated.

like image 67
ayanami Avatar answered Oct 31 '25 06:10

ayanami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!