Skip to content

Instantly share code, notes, and snippets.

@ibeex
Created October 14, 2011 20:04
Show Gist options
  • Select an option

  • Save ibeex/1288159 to your computer and use it in GitHub Desktop.

Select an option

Save ibeex/1288159 to your computer and use it in GitHub Desktop.
Python LDAP (ActiveDirectory) authentication
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 = '%s@xxx.xx' % username
# your password
LDAP_PASSWORD = password
base_dn = 'DC=xxx,DC=xxx'
ldap_filter = 'userPrincipalName=%s@xxx.xx' % 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
@herophil322

Copy link
Copy Markdown

Hello, i'd like to know under which license this code was puplished? Is it opensource? Cant find any information anywere? would like to use it in an academic projekt.

@olivierapex6

Copy link
Copy Markdown

cool thanks! :)

@madansirish

Copy link
Copy Markdown

cool great work

@Satyaa78

Copy link
Copy Markdown

Will use it in my project !!! Thanks :)

@chiragsoni2401

Copy link
Copy Markdown

Great man, it worked for me. Good job!

@cemdrk

cemdrk commented Jul 17, 2019

Copy link
Copy Markdown

which python module did you use for ldap

@ibeex

ibeex commented Jul 17, 2019

Copy link
Copy Markdown
Author

@cemdrk it is from 2011 so I don't remember exactly which module it was. Probably it will work with little modifications with any ldap module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment