【问题标题】:Custom authentication method for Flask-SecurityFlask-Security 的自定义身份验证方法
【发布时间】:2017-01-19 20:12:36
【问题描述】:

我正在使用烧瓶安全性来验证用户身份。我已确保身份验证与 http_auth_required 装饰器一起正常工作 - 正在针对用户存储(在我的情况下为 SQLAlchemyUserDatastore)验证用户,一切都很好。

我现在想使用我自己的身份验证方法(我将使用自定义 LDAP 验证系统),同时仍然利用 Flask-Security 为我提供的功能(例如current_user)。我写了一个自定义装饰器,看起来像这样:

def authenticate_with_ldap(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if not request.authorization:
            return unauthorized_user_handler()
        user = user_datastore.get_user(request.authorization.username)
        if not user or not authenticate_with_ldap(user.email, user.password):
            return unauthorized_user_handler()
        return func(*args, **kwargs)
    return wrapper

但是,当我查看 http_auth_required 装饰器时,我发现它使用了一个名为 _check_http_auth 的私有函数,该函数正在做一些我不能在不访问私有成员的情况下自己做的事情,比如将用户设置为请求上下文堆栈的顶部和发送信号。代码如下所示:

def _check_http_auth():
    auth = request.authorization or BasicAuth(username=None, password=None)
    user = _security.datastore.find_user(email=auth.username)

    if user and utils.verify_and_update_password(auth.password, user):
        _security.datastore.commit()
        app = current_app._get_current_object()
        _request_ctx_stack.top.user = user
        identity_changed.send(app, identity=Identity(user.id))
        return True

    return False

所以我的问题是:在充分利用 Flask-Security 的同时,拥有自定义身份验证方法的正确方法是什么?

【问题讨论】:

    标签: python flask-login flask-security


    【解决方案1】:

    您可以通过快速的猴子补丁来完成此操作。不理想,但我不确定在 Flask-Security 团队以更优雅的方式处理此问题之前您还能做什么。

    import flask_security
    
    def verify_and_update_password_custom(password, user):
        return user.verify_password(password)    
    
    flask_security.forms.verify_and_update_password = verify_and_update_password_custom
    

    我不确定它是否在其他地方使用。以上适用于我自己的目的。如果它确实在其他地方被调用,您只需要在任何地方将其修补到位。

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 2014-04-20
      • 2014-12-13
      • 2016-08-05
      • 2020-12-05
      • 2015-04-27
      • 2014-01-12
      • 2016-09-05
      • 2021-04-21
      相关资源
      最近更新 更多