Why does the authenticate fails even if the email and password are correct in django?

class login(APIView):
def post(self,request):
    email=request.data.get('email')
    password=request.data.get('password')
    user=get_user_model()
    print("user model",user)
    print(email,password)
    user = User.objects.get(email=email)
    if str(password) == str(user.password):
        print("authenticated")
    # return Response({'status':200})
    user = authenticate(request,email=email,password=password)
    if user is not None:
        # User is authenticated, you can proceed with further logic
        return Response({'status':200,'msg': 'Login successful'})
    else:
        return Response({'status':401,'error': 'Invalid credentials'})

I have made a custom user model with email and password and i am making post request via postman and sending data in JSON format .I have used a simple password check and the password matched as expected but the authenticate function is not giving correct results . What can be the possible cause for this behavior and how to solve it?

First of all, when comparing passwords, you should not convert them to strings and compare directly and that's because Django stores passwords using hashing algorithm for security reasons. Instead, you should use the check_password method provided by Django's user model like this:

if check_password(password, user.password):

Then in your settings file you have to set the AUTHENTICATION_BACKENDS like this to include your authentication model:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'yourAppName.authenticationModule.YourCustomUserBackend',
]
Back to Top