-
-
Save born2discover/4f9c79589212f5d894e811c42f38e228 to your computer and use it in GitHub Desktop.
Python LDAP (ActiveDirectory) authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ldap | |
def check_credentials(username, password): | |
"""Verifies credentials for username and password. | |
Returns None on success or a string describing the error on failure | |
# Adapt to your needs | |
""" | |
LDAP_SERVER = 'ldap://xxx' | |
# fully qualified AD user name | |
LDAP_USERNAME = '%[email protected]' % username | |
# your password | |
LDAP_PASSWORD = password | |
base_dn = 'DC=xxx,DC=xxx' | |
ldap_filter = 'userPrincipalName=%[email protected]' % username | |
attrs = ['memberOf'] | |
try: | |
# build a client | |
ldap_client = ldap.initialize(LDAP_SERVER) | |
# perform a synchronous bind | |
ldap_client.set_option(ldap.OPT_REFERRALS,0) | |
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) | |
except ldap.INVALID_CREDENTIALS: | |
ldap_client.unbind() | |
return 'Wrong username ili password' | |
except ldap.SERVER_DOWN: | |
return 'AD server not awailable' | |
# all is well | |
# get all user groups and store it in cerrypy session for future use | |
cherrypy.session[username] = str(ldap_client.search_s(base_dn, | |
ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf']) | |
ldap_client.unbind() | |
return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ldap | |
LDAP_SERVER = 'ldap://example.com' | |
BASE_DN = 'dc=example,dc=com' # base dn to search in | |
LDAP_LOGIN = 'ldap_login' | |
LDAP_PASSWORD = 'ldap_password' | |
OBJECT_TO_SEARCH = '[email protected]' | |
ATTRIBUTES_TO_SEARCH = ['memberOf'] | |
connect = ldap.initialize(LDAP_SERVER) | |
connect.set_option(ldap.OPT_REFERRALS, 0) # to search the object and all its descendants | |
connect.simple_bind_s(LDAP_LOGIN, LDAP_PASSWORD) | |
result = connect.search_s(BASE_DN, ldap.SCOPE_SUBTREE, OBJECT_TO_SEARCH, ATTRIBUTES_TO_SEARCH) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment