Wednesday, 19 October 2016

LDAP Authentication using Python


What is LDAP?

    LDAP is a protocol for accessing a directory. A directory contains objects. Generally those related to users, groups, computers, printers and so on; company structure information (although frankly you can extend it and store anything in there).  LDAP gives you query methods to add, update and remove objects within a directory (and a bunch more, but those are the central ones).

How does LDAP works with Active Directory?
   
    LDAP client communicate with LDAP server by quering and ask for the information required. To access the LDAP service, the LDAP client first must authenticate itself to the service.
   
    That is, it must tell the LDAP server who is going to be accessing the data so that the server can decide what the client is allowed to see and do.
   
    If the client authenticates successfully to the LDAP server, then when the server subsequently receives a request from the client, it will check whether the client is allowed to perform the request and returns data.

Python code:
    This snippet says how to connect with LDAP service and to perform authentication.


Here we use python code to authenticate LDAP. The “Python-ldap”  library acts as LDAP client service.The function get_client used to establish connection between LDAP client and server.
  • LDAP client service first initialize the LDAP url(Check LDAP server is reachable or not)
  • Then it adds the username to base_dn (base_dn is nothing but the directory structure of the user) , so we add username with base_dn to say the client to check the user available in that location or not (i.e simply authenticate)  
  • ldap_user = CN=<username>,<Directory structure>
  • Finally authentication done with bind the user details with connection object.
Sample output:
conn ==>  <ldap.ldapobject.SimpleLDAPObject instance at 0x7f62918a5b00>




References: