python - Flask 和 Ldap3 不能很好地一起玩
问题描述
我正在为我的公司构建一个内部应用程序,并且正在研究使用 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 页面和以下终端错误:
引发 LDAPBindError(error) ldap3.core.exceptions.LDAPBindError: 自动绑定不成功 - invalidCredentials
解决方案
使用 时auto_bind=True
,LDAPBindError
如果凭据错误,将引发 a。我可以看到两个解决方案(第一个对我来说似乎更 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')
推荐阅读
- grammar - 语法:如何添加优先级
- excel - 宏 Excel:将单元格值按多列拆分为多行并保留其他数据
- python - 如果列在列表中包含超过 x 个值,则删除组
- sql - 这是对 Range-Hash 分区的正确解释吗?
- java - 清理/验证变量以避免跨站点脚本攻击
- c++ - 包含两个整数的代码如何逐步操作 C++?
- spring - Spring JPA:我应该如何创建/使用查找表?
- http - 在另一个选项卡中打开 http 目标并同时将数据传递给服务器
- azure-devops - 如何使用 Azure DevOps Pipeline 部署多个 ARM
- c# - Serilog 日志异常和其他属性