Flask+ldap3认证报错LDAPPasswordIsMandatoryError求助
问题分析
LDAPPasswordIsMandatoryError: password is mandatory in simple bind 错误说明传入LDAP绑定请求的密码为空,根源出在表单字段定义异常和未正确触发表单验证两个环节:
LoginForm.py中密码字段的定义存在语法错误(多余空行、缩进混乱),导致字段无法正确接收用户输入;main.py中仅通过request.method == 'POST'判断提交,未触发Flask-WTF的表单验证规则,空密码会直接传入LDAP认证函数。
解决方案
1. 修复LoginForm.py的语法错误
修正密码字段的格式问题,同时移除重复的autofocus属性(仅保留用户名字段的自动聚焦):
from main import app from flask_wtf import Form from wtforms import StringField, PasswordField, validators class LoginValidation(Form): user_name_pid = StringField('', [validators.DataRequired()], render_kw={'autofocus': True, 'placeholder': 'Enter User'}) user_pid_Password = PasswordField('', [validators.DataRequired()], render_kw={'placeholder': 'Enter your login Password'})
2. 修正main.py的表单验证逻辑
改用Flask-WTF提供的form.validate_on_submit()方法,确保表单验证规则生效后再执行LDAP认证:
@app.route('/login', methods=['GET','POST']) def index(): form = LoginValidation() if form.validate_on_submit(): login_id = form.user_name_pid.data login_password = form.user_pid_Password.data login_msg = global_ldap_authentication(login_id, login_password) if login_msg == "Success": success_message = "*** Authentication Success " return render_template('success.html', success_message=success_message) else: error_message = f"*** Authentication Failed - {login_msg}" return render_template("error.html", error_message=str(error_message)) return render_template('login.html', form=form)
3. 可选:增加LDAP认证函数的参数校验
在global_ldap_authentication.py中添加前置校验,提前拦截空值避免触发LDAP异常:
def global_ldap_authentication(user_name, user_pwd): # 新增参数校验 if not user_name or not user_pwd: return "Username or password cannot be empty" ldap_user_name = user_name ldap_user_pwd = user_pwd # 后续原有代码保持不变 ldsp_server = f"ldap://localhost:389" root_dn = "dc=example,dc=org" user = f'cn={ldap_user_name},{root_dn}' print(user) server = Server(ldsp_server, get_info=ALL) connection = Connection(server, user=user, password=ldap_user_pwd) if not connection.bind(): print(f" *** Cannot bind to ldap server: {connection.last_error} ") l_success_msg = f' ** Failed Authentication: {connection.last_error}' else: print(f" *** Successful bind to ldap server") l_success_msg = 'Success' return l_success_msg
内容的提问来源于stack exchange,提问作者ryansmith174
相关产品推荐
相关产品推荐

