My setup: Django-3.0, Python-3.8, django_auth_ldap
I have LDAP Server (Active Directory Server) in my organization.
I am building a Django Application which serves some operations for all the users.
I know Django has built-in User Authentication mechanism, But it authenticates if users are present in User Model Database.
But my requirement is.
All user entries are in LDAP Server(Active Directory). Using proper user credentials LDAP server authenticates me.
I Created a Login Page in Django 'accounts' app,
1. whenever I enter username and password from Login Page, it should Authenticate using My Organization LDAP Server.
2. After Login I have to hold the session for the logged in user for 5 active minutes. (Django auth session)
I saw django_auth_ldap package gives some insight for my purpose.
I have these contents in settings.py.
import ldap
##Ldap settings
AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com"
AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0}
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com"
AUTH_LDAP_START_TLS = True
#Register authentication backend
AUTHENTICATION_BACKENDS = [
"django_auth_ldap.backend.LDAPBackend",
]
Calling authenticate in views.py.
from django_auth_ldap.backend import LDAPBackend
def accounts_login(request):
username = ""
password = ""
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
auth = LDAPBackend()
user = auth.authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
error = "Authentication Failed"
return render(request, "accounts/login.html", 'error':error)
return render(request, "accounts/login.html")
But using above method always authenticate fails with the LDAP Server.
If I call using normal python simple_bind_s(), authentication is working fine to same LDAP server.
import ldap
def ldap_auth(username, password):
conn = ldap.initialize(myproj.settings.LDAP_AUTH_URI)
try:
ldap.set_option(ldap.OPT_REFERRALS, 0)
#ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
conn.simple_bind_s(username, password)
except ldap.LDAPError as e:
return f'failed to authenticate'
conn.unbind_s()
return "Success"
Can anybody suggest me to make LDAPBackend Authentication work as per my requirement ?
Note: I do not have admin permission of LDAP Server.