Flask和Ldap3在一起打得不好



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

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

@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页和以下终端错误:

引发LDAPBindError(error(ldap3.core.exceptions.LDAPBindError:自动绑定不成功-invalidCredentials

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

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

最新更新