Flask-HTTPAuth:如何向@auth.verify_password装饰的函数传额外参数?
给Flask-HTTPAuth的验证函数传递参数的方法
下面两种方法都能在不触发错误的前提下,给@auth.verify_password装饰的验证函数传参数(比如身份验证开关、调试标识这类):
方法一:给auth实例添加自定义属性
直接在HTTPBasicAuth的实例上挂载需要的参数,验证函数内部直接访问即可,这是最简单的方式:
from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() # 给auth实例添加自定义参数 auth.auth_enabled = True # 身份验证开关 auth.debug_mode = False # 调试/详细日志开关 authorized_users_dict = { "test_user": "pbkdf2:sha256:260000$xxxxxx$xxxxxx" # 替换成实际的哈希密码 } @auth.verify_password def authenticate(username, password): # 先判断是否开启验证 if not auth.auth_enabled: return True # 关闭验证时直接放行 if username in authorized_users_dict: if check_password_hash(authorized_users_dict[username], password): # 调试模式下打印日志 if auth.debug_mode: print(f"用户 [{username}] 身份验证通过") return True return False @app.route('/protected') @auth.login_required def protected_route(): return "这是需要验证的页面" if __name__ == '__main__': app.run(debug=True)
方法二:用类封装验证逻辑(适合复杂场景)
如果参数较多或者需要更灵活的配置,可以把验证逻辑和参数封装到类里,再把类的方法注册为验证函数:
from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() class AuthHandler: def __init__(self, auth_enabled=True, debug_mode=False): self.auth_enabled = auth_enabled self.debug_mode = debug_mode self.authorized_users = { "test_user": "pbkdf2:sha256:260000$xxxxxx$xxxxxx" } def verify(self, username, password): if not self.auth_enabled: return True if username in self.authorized_users: if check_password_hash(self.authorized_users[username], password): if self.debug_mode: print(f"验证日志:用户 {username} 登录成功") return True return False # 初始化处理器,传入自定义参数 auth_handler = AuthHandler(auth_enabled=True, debug_mode=True) # 将类的方法注册为验证函数 auth.verify_password(auth_handler.verify) @app.route('/protected') @auth.login_required def protected_route(): return "这是需要验证的页面" if __name__ == '__main__': app.run(debug=True)
这两种方法都不会破坏Flask-HTTPAuth的原有逻辑,也不会触发错误,根据你的场景选择即可。
内容的提问来源于stack exchange,提问作者mirekphd
相关产品推荐
相关产品推荐

