Django-rest-framework specific authentication backend

37 views
Skip to first unread message

Rafael Almeida

unread,
Aug 9, 2019, 6:17:15 AM8/9/19
to Django REST framework
I have been trying to find a related topic but there seems to be none. Please point me to it if it has been suggested before.

In my Django application I have 3 types of login backend. User login backend, admin login backend and api login backend.
All persist login attempts on the backend. It is important then to choose the right login backend immediately. To circumvent this problem I had to implement my own authentication method.

def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
backend = ModelBackend()
backend_path = settings.REST_FRAMEWORK_AUTH_BACKEND
try:
user = _authenticate_with_backend(backend, backend_path, request, credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)
return
if user is None:
user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)
return
# Annotate the user object with the path of the backend.
user.backend = backend_path
return user

It's more or less a copy paste of what is in django/contrib/auth/__init__.py

What are your thoughts?
Reply all
Reply to author
Forward
0 new messages