Search code examples
pythondjangoauthenticationdjango-authentication

Authentication without a passwrod Django


As the title states I'm trying to authenticate a user without a password. I've already used this: django authentication without a password to solve my problem with on of my apps (on Django 2.0), but I want to do the same thing in another app but It's on Django 2.1. When I do the same implementation my custom authenticate fuction is never called. Thus it doesn't work.

Current setup in auth_backend.py:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class PasswordlessAuthBackend(ModelBackend):
    """Log in to Django without providing a password.

    """
    def authenticate(self, username=None):
        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

setup in settings.py:

AUTHENTICATION_BACKENDS = [
# auth_backend.py implementing Class PasswordlessAuthBackend inside yourapp folder
    'yourapp.auth_backend.PasswordlessAuthBackend', 
# Default authentication of Django
    'django.contrib.auth.backends.ModelBackend',
]

but when I try in my views

user = authenticate(username=user.username)

It never hits my custom authentication method. Any and all help is appreciated!


Solution

  • So I solved my own issue thanks to documents here: https://docs.djangoproject.com/en/2.1/topics/auth/customizing/

    All I had to do was authetnicate function in auth_backend.py from

    def authenticate(self, username=None):
    

    to

    def authenticate(self, request, username=None):
    

    In the documentation it said you can also change the class delcaration not to include ModelBackend, but it worked either way.