2016-03-03 69 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