zochamx zochamx - 10 days ago 5
Python Question

Python ldap3 rebind method doesn't raise error

I have the following code

from ldap3 import Server, Connection, SUBTREE, ALL_ATTRIBUTES, LDAPBindError

...
...

def search(self, id):
if not self._connect.bind():
print('error in bind', self._connect.result)
else:
self._connect.search(
search_base=self._base_dn,
search_filter='(uid='+id+')',
search_scope=SUBTREE
)
userdn = self._connect.response[0]['dn']
try:
self._connect.rebind(user=userdn, password='password')
print(self._connect.result)
except LDAPBindError:
print('error in rebind', self._connect.result)

self._connect.unbind()
pass


According to
python-ldap3
documentation the
rebind
method should raise an
LDAPBindError


Docs:

# import class and constants
from ldap3 import Server, Connection, ALL, LDAPBindError

# define the server
s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema

# define the connection
c = Connection(s, user='user_dn', password='user_password')

# perform the Bind operation
if not c.bind():
print('error in bind', c.result)

try:
c.rebind(user='different_user_dn', password='different_user_password')
except LDAPBindError:
print('error in rebind', c.result)



In case the credentials are invalid or if the server doesn’t allow you to rebind the server could abruptly close the connection. This condition is checked by the rebind() method and an LDAPBindError exception will be raised if caugh. Link to this


The problem is that although everything seems working fine, i can verify that from printing the
result
property.

On succeful rebind:
{'result': 0, 'description': 'success', 'type': 'bindResponse', 'message': '', 'dn': '', 'referrals': None, 'saslCreds': None}


On failed rebind:
{'type': 'bindResponse', 'dn': '', 'result': 49, 'description': 'invalidCredentials', 'message': '', 'referrals': None, 'saslCreds': None}


Although in failed rebind no exception is raised. Did i understand anything wrong and shouldn't raise an error? Otherwise why it doesn't, have i sth wrong?

Thanks for any help.

Answer

docs are outdated. The rebind() method behaves like the bind(). It return True if bind is successful and false if unsuccessful. If you want to have an exception raised when credentials are invalid you must use the raise_exceptions=True parameter in the Connection() definition.

The LdapBindError exception is only raised if the server closes the connection when trying to bind again. Keep in mind that network errors always raise an exception, even if raise_exceptions is set to False.

Will update the docs soon (I'm the author of ldap3).