pythonflaskldap3

Flask and Ldap3 not playing nicely together


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

@authBP.route('login', methods=['GET', 'POST'])
def loginView():
    form = LoginForm()
    if form.validate_on_submit():
        server = Server(current_app.config['LDAP_SERVER'], get_info=ALL)

        connection = Connection(server,
                                user='domain\{initials}'.format(initials=form.init.data),
                                password=form.passwd.data,
                                auto_bind=True)

        if not connection.bind():
            flash('not authenticated')
        else:
            flash('authenticated')

        return redirect(url_for('indexBP.indexView'))  
       
    return render_template('auth/login.html', form=form)

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


Solution

  • 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):

    # 1st one with try/except
        try:
            Connection(server, user='user', password='****', auto_bind=True)
            flash('authenticated')
        except LDAPBindError:
            flash('not authenticated')
    
    # 2d one with if and without auto_bind
    
        conn = Connection(server, user='user', password='****')
        if conn.bind():
            flash('authenticated')
        else:
            flash('not authenticated')