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
?
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.