I’m building an internal app for my company, and are looking into using ldap3 to connect to our exchange server to validate login credentials.
I am integrating into a flask app and have a login view with the following code
JavaScript
x
20
20
1
@authBP.route('login', methods=['GET', 'POST'])
2
def loginView():
3
form = LoginForm()
4
if form.validate_on_submit():
5
server = Server(current_app.config['LDAP_SERVER'], get_info=ALL)
6
7
connection = Connection(server,
8
user='domain{initials}'.format(initials=form.init.data),
9
password=form.passwd.data,
10
auto_bind=True)
11
12
if not connection.bind():
13
flash('not authenticated')
14
else:
15
flash('authenticated')
16
17
return redirect(url_for('indexBP.indexView'))
18
19
return render_template('auth/login.html', form=form)
20
The above code works fine when I login using my actual credentials, but when I try to login using wrong credentials I do not get a flash message, but in stead get an error 500 page and the following terminal error:
raise LDAPBindError(error) ldap3.core.exceptions.LDAPBindError: automatic bind not successful – invalidCredentials
Advertisement
Answer
When you use auto_bind=True
, a LDAPBindError
will be raised if credentials are wrong. I can see two solutions (the first one seems more pythonic to me):
JavaScript
1
15
15
1
# 1st one with try/except
2
try:
3
Connection(server, user='user', password='****', auto_bind=True)
4
flash('authenticated')
5
except LDAPBindError:
6
flash('not authenticated')
7
8
# 2d one with if and without auto_bind
9
10
conn = Connection(server, user='user', password='****')
11
if conn.bind():
12
flash('authenticated')
13
else:
14
flash('not authenticated')
15