I have a Django project in which I want to authenticate users against an Active Directory. Therefore, I am using the django-python3-ldap framework. I am able to sync users( ./manage.py ldap_sync_users
), grant superuser admin access, and login to the default Django admin page using the framework as backend. However, when I try to authenticate on my site, the user state remains AnonymousUser
.
views.py
def login(request):
try:
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend=django_python3_ldap)
context = {'user': user}
return render(request, 'website/home.html', context)
else:
context = {'': ''}
return render(request, 'website/login.html', context)
except:
print()
login.html
<!-- Main content --> <section class="hero is-success is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="column is-4 is-offset-4"> <div class="box"> <figure class="avatar"> <img src=""> </figure> <form method="post"> {% csrf_token %} <div class="field"> <div class="control"> <input class="input is-large" type="text" placeholder="Username" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="password" placeholder="Password"> </div> </div> <div class="field"> <label class="checkbox"> <input type="checkbox"> Remember Me </label> </div> <button class="button is-block is-danger is-info is-large is-fullwidth">Login</button> {% endblock %} </form> </div> </div> </div> </div> </section>
imports
from django.contrib.auth import authenticate, login
import django_python3_ldap
backend
AUTHENTICATION_BACKENDS = ('django_python3_ldap.auth.LDAPBackend',)
urls.py
path('login', auth_views.login, {'template_name': 'website/login.html'}, name='login'),
I see possibly two issues the backend is not pointing to a valid backend. Also your try except is a bit dangerous please remove it. Unless you are testing never use a blank except. Use something like except Exception as e: print(e)
. The reason I say that is the blank except was hiding the invalid backend error.
login(request, user, backend=django_python3_ldap)
# Should be
login(request, user, backend=django_python3_ldap.auth.LDAPBackend)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.