1
votes

When I input the same username and password as in the database it shows "invalid credentials" instead of "Success".

def login(request): if request.method == 'POST':

    username           = request.POST.get('user')
    password1          = request.POST.get('password1')
    a                  = authenticate( username=username, password=password1)
    if a is not None:
        return HttpResponse("Success")
    else:
        return HttpResponse("Invalid Credentials")
return render(request, 'login.html')
1
How did you create a user? Is the password hashed?Willem Van Onsem
actually, I directly inserted the username and password in the database.Also, I have hashed passwords.But I'm trying to deal with the directly inserted valuesRahul S Dev
well then this will not work. Django hashes the passwords when you create a user, and also checks if the hash matches. Storing raw passwords in the database is a severe security threat.Willem Van Onsem

1 Answers

1
votes

The problem is not with the authentication itself, but with creating users. You can not create users with raw passwords in the database. Django stores hashed passwords in the database. By default the PBKDF2 hasher is used, although you can configure that. That means that a password looks like:

algorithm$iterations$salt$hash

The authentication module will hash the password you give, and check if this matches.

You can make use of the createsuperuser management command [Django-doc] to make a superuser:

django-admin createsuperuser

or you can change the password of a user with the changepassword management command [Django-doc]:

django-admin changepassword username

For normal users, you can make for example through the admin pages, or with the the .create_user(…) method [Django-doc] in the shell:

$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> get_user_model().objects.create_user(username='username', password='thepassword')
<User: username>