2016-03-03 26 views
1

我正在使用Flask-Security扩展,并且不能为我的生活弄清楚扩展初始化时扩展中的哪个位置可以传入未经授权的处理程序。这对我来说很重要,因为我不想在没有必要权限的情况下将用户重定向到另一个端点。我希望他们在他们所在的网址中查看它,以便他们保留他们没有权限访问的url的上下文。我的解决办法是猴子补丁到扩展方法的第一个请求到来之前:烧瓶安全未经授权的回调

@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

我有同样的问题 - 我想我的应用程序返回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