Skip to content

Instantly share code, notes, and snippets.

@pythoninthegrass
Forked from femmerling/authenticate.py
Last active May 14, 2019 19:43
Show Gist options
  • Save pythoninthegrass/1940128062c15bc20144974d6743e603 to your computer and use it in GitHub Desktop.
Save pythoninthegrass/1940128062c15bc20144974d6743e603 to your computer and use it in GitHub Desktop.
I have to create user authentication using python-ldap. After googling around and trying out stuffs, this is the final code for you to use. Please remember to adjust the user_dn, and base_dn accordingly to the format used in your LDAP server.
# to be able to import ldap run pip install python-ldap
import ldap
if __name__ == "__main__":
ldap_server="x.x.x.x"
username = "someuser"
password= "somepassword"
# the following is the user_dn format provided by the ldap server
user_dn = "uid="+username+",ou=someou,dc=somedc,dc=local"
# adjust this to your base dn for searching
base_dn = "dc=somedc,dc=local"
connect = ldap.initialize(ldap_server) # https://gist.github.com/femmerling/5097365#gistcomment-2751440
search_filter = "uid="+username
try:
#if authentication successful, get the full user data
connect.bind_s(user_dn,password)
result = connect.search_s(base_dn,ldap.SCOPE_SUBTREE,search_filter)
# return all user data results
connect.unbind_s()
print result
except ldap.LDAPError:
connect.unbind_s()
print "authentication error"
@pythoninthegrass
Copy link
Author

Alternative from John Mudd.

import ldap
conn = ldap.open("ldap.company.com")
conn.simple_bind_s("[email protected]", "mypassword")

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