How to login using LDAP in Django - django

I am trying to enable LDAP server for login and authenticate in my Django application. I read django-auth-ldap tutorial and done all the changes in settings.py.
But I not able to login from LDAP server users, Django always try to login only form local database.
What i have to do and change any thing while login user? any changes is required in view.py authenticate() function for login.
My code snippets are below :
settings.py
AUTH_LDAP_SERVER_URI = 'ldap://my_domain.com'
AUTH_LDAP_BIND_DN = 'cn=admin,dc=my_domain,dc=com'
AUTH_LDAP_BIND_PASSWORD = 'My_password'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
'ou=users,dc=my_domain,dc=com',
ldap.SCOPE_SUBTREE,
'(uid=%(user)s)',
)
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
'ou=django,dc=my_domain,dc=com',
ldap.SCOPE_SUBTREE,
'(objectClass=groupOfNames)',
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn')
# Simple group restrictions
AUTH_LDAP_REQUIRE_GROUP = 'cn=enabled,ou=django,ou=groups,dc=my_domain,dc=com'
AUTH_LDAP_DENY_GROUP = 'cn=disabled,ou=django,ou=groups,dc=my_domain,dc=com'
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
"username": "uid",
"passsword": "userPassword"
}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
'is_active': 'cn=active,ou=django,ou=groups,dc=my_domain,dc=com',
'is_staff': 'cn=staff,ou=django,ou=groups,dc=my_domain,dc=com',
'is_superuser': 'cn=superuser,ou=django,ou=groups,dc=my_domain,dc=com',
}
# This is the default, but I like to be explicit.
AUTH_LDAP_ALWAYS_UPDATE_USER = True
# Use LDAP group membership to calculate group permissions.
AUTH_LDAP_FIND_GROUP_PERMS = True
# Cache distinguised names and group memberships for an hour to minimize
# LDAP traffic.
AUTH_LDAP_CACHE_TIMEOUT = 3600
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
#view.py
from django.contrib.auth import authenticate, login
def user_login(request):
user = authenticate(username = username, password = password)
login(request, user)
return HttpResponseRedirect('/')
Any code changes required in user_login() function or djagno automatically checks and authenticate users from LDAP as well as local database.
I am not sure which Django function will used for login purpose.
Any one please help me.

I was struggling for this soo long. and finally its working
with django-auth-ldap on Django 2.2 + Python 3.6.8 .
This is my settings.py
and its working fine.
import ldap
from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType
AUTH_LDAP_SERVER_URI = 'ldap://192.168.122.222'
AUTH_LDAP_BIND_DN = 'CN=Django Admin,CN=Users,DC=hqvfx,DC=com'
AUTH_LDAP_BIND_PASSWORD = 'MyPassword'
AUTH_LDAP_USER_SEARCH = LDAPSearch('OU=all,OU=LSA_Users,DC=hqvfx,DC=com',ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)')
AUTH_LDAP_GROUP_SEARCH = LDAPSearch('OU=HQ_Groups,DC=hqvfx,DC=com',ldap.SCOPE_SUBTREE, '(objectClass=top)')
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
AUTH_LDAP_MIRROR_GROUPS = True
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
'username': 'sAMAccountName',
'first_name': 'displayName',
'last_name': 'sn',
'email': 'mail',
}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
'is_active': 'CN=all, OU=HQ_Groups, DC=hqvfx, DC=com',
'is_staff': 'CN=all, OU=HQ_Groups, DC=hqvfx, DC=com',
'is_superuser': 'CN=all, OU=HQ_Groups, DC=hqvfx, DC=com',
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_TIMEOUT = 3600
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)

Related

Django LDAP - raised SIZELIMIT_EXCEEDED

Django application can connect to the LDAP server flawlessly.
While login I'm getting the below error,
search_s('DC=xx,DC=yyy,DC=com', 2, " (objectClass=organizationalPerson)") raised SIZELIMIT_EXCEEDED(('msgtype': 100,
'msgid': 2, 'result': 4, 'desc': 'Size limit exceeded', 'ctrls': []})
How to set the SIZELIMIT in LDAP configuration
please help me with this issue.
My settings.py,
# Baseline Configuration
AUTH_LDAP_SERVER_URI='Ldap://xyz.server.com'
AUTH LDAP CONNECTION OPTIONS = {
ldap.OPT_REFERRALS: 0
}
LDAP_IGNORE_CERT_ERRORS = True
AUTH_LDAP_BIND_DN = 'CN=dev,OU=Accounts,DC=xy,DC=qwerty, DC=com'
AUTH_LDAP_BIND_PASSWORD = 'qwerty123'
AUTH_LDAP_USER_SEARCH = LDAPSearch(
'DC=xy,DC=qwerty, DC=com',
ldap.SCOPE_SUBTREE,
"(objectClass=organizationalPerson)",
['cn']
)
LDAP_USER_ATTRIBUTES="cn,sn,givenName,displayName,employeeID,mail"
LDAP_BASE_DN = "DC=xy,DC=qwerty, DC=com"
LDAP USE SSL= True
LDAP_SEARCH_DOMAINS = "au.pbs,branch1,branch?"
AUTH_LDAP_GROUP BASE = "OU=Accounts,DC=xy,DC=qwerty, DC=com"
AUTH_LDAP_GROUP_FILTER = '(objectClass=posixGroup)'
AUTH LDAP GROUP SEARCH = LDAPSearch(
AUTHLDAP_GROUP_BASE,
ldap.SCOPE_SUBTREE,
AUTH LDAP GROUP FILTER
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType (name_attr="cn")
AUTH_LDAP _USER_ATTR_MAP = {
'first name': 'givenName',
"last name': 'sn',
'email':'email'
}

Can we check whether a user is part of an Organizational Units instead of Groups in Django LDAP?

In my LDAP directory, Users are added to Organizational Units instead of groups. How can I check whether a user is a part of an Organizational Unit using Django LDAP ?
My settings.py file:
AUTH_LDAP_SERVER_URI = 'ldap://qwery'
AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True
AUTH_LDAP_BIND_DN = 'dndndn'
AUTH_LDAP_BIND_PASSWORD = 'pwdpwd'
AUTH_LDAP_USER_SEARCH = LDAPSearchUnion(
LDAPSearch('ou=abbb,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"),
LDAPSearch('ou=ammmm,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"),
LDAPSearch('ou=addddd,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"),
LDAPSearch('ou=ahhhhh,dc=xxx,dc=net', ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"),
)
AUTH_LDAP_CACHE_TIMEOUT = 0
AUTHENTICATION_BACKENDS = [
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
]
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
"name": "cn",
"username": "sAMAccountName",
"department":"distinguishedName"
}
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"OU=addddd,DC=xxx,DC=net",
ldap.SCOPE_SUBTREE,
"(objectClass=*)")
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_USER_MODEL = 'login.Account'
AUTH_LDAP_USER_FLAGS_BY_GROUP= {
"is_it": "OU=IT,OU=ahhhh,DC=xxx,DC=net",
}
Thank you
You would need to determine the FDN into the RDN parts to determine which OU the user in within.
You can look at an example at: https://www.python-ldap.org/en/python-ldap-3.3.0/reference/ldap-dn.html#examples

AnonymousUser with django.test.client.login()

I'm testing login function.
def setUpClass(cls):
super(BasePage_loggedin, cls).setUpClass()
cls.selenium = WebDriver()
cls.client = Client()
cls.user_1 = MyUser.objects.create_user(username='myself',password='12345')
cls.client.login(username=cls.user_1.username, password=cls.user_1.password)
# create session cookie:
session = SessionStore()
session[SESSION_KEY] = cls.user_1.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session[HASH_SESSION_KEY] = cls.user_1.get_session_auth_hash()
session.save()
# Finally, create the cookie dictionary
cookie = {
'name': settings.SESSION_COOKIE_NAME,
'value': session.session_key,
'secure': False,
'path': '/',
}
# add the session cookie
cls.selenium.get('{}'.format(cls.live_server_url))
cls.selenium.add_cookie(cookie)
cls.selenium.refresh()
cls.selenium.get('{}'.format(cls.live_server_url))
So I can pass the login page, but then, when I do request.user to check the data for this user, it's an AnonymousUser
When you're creating the user that way - I believe it has to do with the password. Setting the password to a string like that doesn't do what you think it would do.
You could create the user like that - then add this after the user creation but before the login:
cls.user_1.set_password('12345')
cls.user_1.save()
Then login the user with something like this:
cls.client.login(username=cls.user_1.username, password='12345')
I believe it has something to do with the hashing of the password or something along those lines - it's been a while since I stumbled around with it, but I remember having the exact same issue as you.
Something like this should work:
cls.selenium = WebDriver()
cls.client = Client()
cls.user_1 = MyUser.objects.create_user(username='myself',password='12345')
cls.user_1.set_password('12345')
cls.user_1.save()
cls.client.login(username=cls.user_1.username, password='12345')
Please check your settings.py and try below codes.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', # needed only up to the test env
'rest_framework.authentication.TokenAuthentication',
)
}

Django Auth is not finding User Account in LDAP

Morning,
I´m implementing Django Auth Ldap in my proyect but it is not working. I checked ldap connection (by Django shell) and returns a search, so I guess python-ldap is working. I used the next:
import ldap
con = ldap.initialize("ldap://hostname")
con.simple_bind_s( "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local", "MyPassword" )
con.search_s( 'DC=CompanyName, DC=local', ldap.SCOPE_SUBTREE, '(objectclass=person)', ['sn'] )
When I try to authenticate an user by web (using Django-Auth-Ldap), authentication always returns None.
Settings. (LDAP Configuration).
AUTH_LDAP_SERVER_URI = "ldap://hostname"
AUTH_LDAP_BIND_DN = "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local"
AUTH_LDAP_BIND_PASSWORD = "MyPassword"
AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=Users, DC=CompanyName, DC=local", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: False
}
from django_auth_ldap.backend import LDAPBackend
View.
def Login(request):
usr = "MyUserName"
pwd = "MyPassword"
if request.method == 'POST':
ldap_backend = LDAPBackend()
user = ldap_backend.authenticate(usr, pwd)
print user
print usr, pwd
In my view, I´m passing to the ldap authentication my user and password which I used for login in the domain. Is that correct?
I got the value "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local" from a command in Directory Active server, kind of: dsquery user
This is the AD Schema:
What Am I Doing wrong?
Thanks guys.
EDITED: The problem is when I define the search throug uid, if I define it as AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=Users, DC=CompanyName, DC=local", ldap.SCOPE_SUBTREE, "(CN=%(user)s)") is working (and, in the view, I must to pass as usr = "MyNameMySurname" instead). How can I Define the search through the username which I used for login it.
Finally... I must to use samAccountName instead of CN. I hope it help you all. Thanks guys.

django auth ldap

I've been trying to get the LDAP -> Django groups mappings working without success. Everything seems to work fine except for the group mapping part. My LDAP backend is Active Directory. I'm using django-auth-ldap 1.0.10.
settings.py:
import ldap, logging
from django_auth_ldap.config import LDAPSearch, ActiveDirectoryGroupType
logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
AUTH_LDAP_SERVER_URI = "ldap://sub.domain.com"
AUTH_LDAP_BIND_DN = 'CN=Bind Account,OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com'
AUTH_LDAP_BIND_PASSWORD = 'passwd'
AUTH_LDAP_USER_SEARCH = LDAPSearch('OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com', ldap.SCOPE_SUBTREE, "(uid=%(user)s)",)
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("OU=Groups,OU=Chicago,DC=sub,DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)")
AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType()
AUTH_LDAP_FIND_GROUP_PERMS = True
#AUTH_LDAP_CACHE_GROUPS = True
#AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
AUTH_LDAP_GLOBAL_OPTIONS = {
ldap.OPT_X_TLS_REQUIRE_CERT: False,
ldap.OPT_REFERRALS: False,
}
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_staff": "CN=SomeGroup,OU=Groups,OU=Chicago,DC=sub,DC=domain,DC=com",
}
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
and my logs
search_s('OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com', 2, '(uid=myuser)') returned 1 objects: CN=My User,OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com
Populating Django user myuser
CN=My User,OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com is a member of CN=SomeGroup,OU=Groups,OU=Chicago,DC=sub,DC=domain,DC=com
search_s('OU=Groups,OU=Chicago,DC=sub,DC=domain,DC=com', 2, '(&(objectClass=groupOfNames)(member=CN=My User,OU=Users,OU=Users,OU=Chicago,DC=sub,DC=domain,DC=com))') returned 0 objects:
Populating Django user profile for myuser
I found the answer. In the group search, i changed the filter to be objectClass=group instead of objectClass=groupOfNames. All is well.