Anteriormente expliqué cómo autenticar contra un servidor LDAP en PHP. Ahora comparto una función para autenticar con LDAP en lenguaje Python.
La siguiente porción de código en lenguaje Python incluye la función check_credentials
. Esta se encarga de autenticar contra un servidor LDAP utilizando el nombre de usuario y contraseña pasados como parámetro:
import ldap import json # LDAP config LDAP_SERVER = "ldap://ldap.linuxito.com" LDAP_BASE_DN = "ou=people,dc=linuxito,dc=com" LDAP_ATTRS = ["cn", "dn", "sn", "givenName"] def check_credentials(username, password): """ Verifies credentials for username and password against a LDAP server. Returns some of the user attributes on success or a string describing the error on failure. """ ldap_user = "uid=%s,%s" % (username, LDAP_BASE_DN) ldap_filter = "(uid=%s)" % username try: # Build a LDAP client ldap_client = ldap.initialize(LDAP_SERVER) # Set LDAPv3 option ldap_client.set_option(ldap.OPT_PROTOCOL_VERSION,3) # Try to bind as username/password ldap_client.simple_bind_s(ldap_user,password) except ldap.INVALID_CREDENTIALS: ldap_client.unbind() return json.dumps('Wrong username or password.') except ldap.SERVER_DOWN: return json.dumps('LDAP server not available.') # Authentication is OK # Get user attributes defined in LDAP_ATTRS user_info = json.dumps(ldap_client.search_s(LDAP_BASE_DN, ldap.SCOPE_SUBTREE, ldap_filter, LDAP_ATTRS)[0][1]) ldap_client.unbind() return user_info
Es necesario definir algunas variables globales donde establecer la URL del servidor LDAP; el DN base para buscar usuarios dentro del directorio LDAP; y los atributos del usuario que se deseen recuperar.
El proceso de autenticación es extremadamente sencillo. Primero es necesario inicializar una instancia de la clase ldap
y definir las opciones requeridas para la conexión. Luego se intenta conectar con el servidor mediante la función simple_bind_s
. En caso de éxito, se recuperan los atributos del usuario utilizando la función search_s
.
Veamos una salida de ejemplo de la función check_credentials
:
emi@hal9000:~/git_repos/vmware % python Python 2.7.15 (default, May 13 2018, 01:10:00) [GCC 4.2.1 Compatible FreeBSD Clang 4.0.0 (tags/RELEASE_400/final 297347)] on freebsd11 Type "help", "copyright", "credits" or "license" for more information. >>> import ldap_auth >>> ldap_auth.check_credentials("test","1234") 'Wrong username or password.' >>> ldap_auth.check_credentials("estudianto","trustno1") "{'givenName': ['Estudianto'], 'cn': ['Estudianto Mudel'], 'sn': ['Mudel']}" >>> quit()
Referencias