检查 Flask-HTTPAuth 是否在视图中通过身份验证

Check if Flask-HTTPAuth is authenticated inside view

我正在使用 Flask-HTTPAuth 进行身份验证。我想根据请求是否经过身份验证从视图中显示不同的数据。用 auth.login_required 修饰视图只会将其显示给经过身份验证的用户。如何测试请求是否通过 Flask-HTTPAuth 验证?

auth = HTTPBasicAuth()

@app.route("/clothesInfo")
@auth.login_required
def show_info():
    return jsonify(blah blah blah)

您可以用 login_required 修饰 return 和 None 的函数。在未通过身份验证时调用它会 return 错误响应,在经过身份验证时调用它会 return None.

# a dummy callable to execute the login_required logic
login_required_dummy_view = auth.login_required(lambda: None)

def is_authenticated():
    try:
        # default implementation returns a string error
        return login_required_dummy_view() is None
    except HTTPException:
        # in case auth_error_callback raises a real error
        return False

@app.route('/info')
def info():
    if is_authenticated():
        # logged in view

    else:
        # basic view

另见

你想要的其实很容易实现。在您的 verify_password 回调中,当用户未提供凭据时,您将获得设置为 '' 的用户名和密码。您仍然可以从该函数 return True,这将允许匿名用户访问端点。

以下示例演示了此技术:

auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username, password):
    if username == '' or password == '':
        # anonymous user, we still let them in
        g.current_user = None
        return True
    g.current_user = my_verify_function(username, password)
    return g.current_user is not None

@app.route("/clothesInfo")
@auth.login_required
def show_info():
    if g.current_user:
        # prepare data for authenticated users here
        pass
    else:
        # prepare data for anonymous users here
        pass
    return jsonify(data)

自 2020 年 4 月以来,事情变得简单了。

Flask-HTTPAuth 4.0.0 向 login required 添加了 optional 参数来完成此操作。

来自the docs

An optional optional argument can be set to True to allow the route to execute also when authentication is not included with the request, in which case auth.current_user() will be set to None. Example:

@app.route('/private')
@auth.login_required(optional=True)
def private_page():
    user = auth.current_user()
    return "Hello {}!".format(user.name if user is not None else 'anonymous')