zochamx zochamx - 1 year ago 153
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)
userdn = self._connect.response[0]['dn']
self._connect.rebind(user=userdn, password='password')
except LDAPBindError:
print('error in rebind', self._connect.result)


According to
documentation the
method should raise an


# 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)

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

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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download