Flask 和 Ldap3 不能很好地协同工作

Flask and Ldap3 not playing nicely together

我正在为我的公司构建一个内部应用程序,并且正在考虑使用 ldap3 连接到我们的交换服务器以验证登录凭据。

我正在集成到一个烧瓶应用程序中,并使用以下代码获得登录视图

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

当我使用我的实际凭据登录时,上面的代码工作正常,但是当我尝试使用错误的凭据登录时,我没有收到闪现消息,而是收到错误 500 页面和以下终端错误:

raise LDAPBindError(error) ldap3.core.exceptions.LDAPBindError: automatic bind not successful - invalidCredentials

当您使用 auto_bind=True 时,如果凭据错误,将引发 LDAPBindError。我可以看到两个解决方案(第一个对我来说似乎更像 pythonic):

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