Flask Security未经授权的回调

时间:2016-03-03 18:52:41

标签: python flask flask-security

我正在使用Flask-Security扩展程序,并且在我的生活中无法确定扩展程序在初始化扩展时我可以在未经授权的处理程序中传递的位置。这对我很重要,因为我不想在用户没有所需权限时将用户重定向到另一个端点。我希望他们在网址中看到它,因此他们保留了他们无权访问的网址的上下文。我的工作是在第一个请求进入之前将方法修补到扩展上:

@app.before_first_request
def monkey_patch():
    """Monkey patching the flasksecurity callback"""
    current_app.extensions['security']._unauthorized_callback=lambda: abort(401)

然后我使用app.errorhandler来处理错误并返回适当的响应代码。

@app.errorhandler(401)
def unauthorized(e):
    return 'You not authorized to visit this page', 401

有谁知道更好的方法吗?

1 个答案:

答案 0 :(得分:2)

我遇到同样的问题 - 我希望我的应用程序在用户尝试访问受限区域后返回JSON对象而不是redireection到login页面。看起来Flask-Security不提供开箱即用的此类功能。幸运的是,它重用Flask-Login并将其暴露为烧瓶应用程序的成员。

这就是它的工作原理。现在,一旦用户尝试访问使用logi_required装饰器保护的API enpoint,它就会返回JSON对象。

@app.login_manager.unauthorized_handler
def unauth_handler():
    return jsonify(success=False,
                   data={'login_required': True},
                   message='Authorize please to access this page'), 401

希望这有帮助!

UPD :我稍微更新了一下功能,使其更加通用。如果传递的请求是AJAX,那么它将使用JSON对象进行响应,否则使用呈现的页面进行响应。

@app.login_manager.unauthorized_handler
def unauth_handler():
    if request.is_xhr:
        return jsonify(success=False,
                       data={'login_required': True},
                       message='Authorize please to access this page.'), 401
    else:
        return render_template('errors/401.html'), 401
相关问题