我正在使用 Flask-Login 的函式 login() 和 remember=True。
這作業正常。但最近我實作了一個雙因素身份驗證,用戶必須下載一個身份驗證器應用程式才能登錄。
我創建了自己的@tfa_required裝飾器,@login_required以防用戶啟用 TFA。我跟蹤登錄狀態的方法是使用一個會話變數auth_level來了解用戶是否使用 TFA 成功登錄。(附上代碼片段)。
假設用戶登錄到瀏覽器,然后將其關閉。他仍會登錄(因為他登錄時使用的是 remember = True),但他將不得不再次輸入 TFA(auth_level=1——這意味著 TFA 尚未成功——現在而不是auth_level=2)。
我真正想要的是存盤auth_level會話變數,只要 Flask-Login 記住用戶登錄,即使在關閉瀏覽器之后也是如此。
據我了解,Flask-Login 使用不同的會話來存盤與登錄相關的變數,以便用戶在一段時間內仍處于登錄狀態。
auth_level即使關閉瀏覽器,我如何讓客戶端記住?
謝謝你。
# Decorator for TFA-required views
def tfa_login_required(f):
"""Implement additional TFA checking, on top of login_required.
TFA is only checked if it has been activated for the user.
"""
@wraps(f)
@login_required
def decorated_function(*args, **kwargs):
# if the user is authenticated and has tfa enabled but not tfa passed
if (
current_user.tfa_enabled
and session.get('auth_level') != 2
):
return redirect(url_for('auth.login_view'))
# if authenticated proceed normally
else:
return f(*args, **kwargs)
return decorated_function
使用 login_required而不使用tfa_required 的示例:
@auth.route('/logout/')
@login_required
def logout():
logout_user()
session['auth_level'] = 0
session.modified = True
return redirect(url_for('main.home'))
使用 tfa_required 和 login_required 的示例:
@main.route('/some_route/', methods=['GET'])
@tfa_login_required
def some_route():
do_some_work_that_requires_full_authentication()
uj5u.com熱心網友回復:
您可能正在尋找 this
默認情況下,如果選項卡關閉,Flask 會洗掉所有會話資料。為了使其永久,請執行以下操作:
@app.before_request
def set_permanent_session():
session.permanent = True
uj5u.com熱心網友回復:
我最終使用 Flask-Login cookie 本身將變數包含在 Flask-Login cookie 中。作為參考,這里是代碼:
from flask_login import (
....
COOKIE_DURATION,
COOKIE_SECURE,
COOKIE_HTTPONLY,
encode_cookie,
)
在視圖函式中url_for(...),我沒有回傳 ,而是make_response()使用以下內容創建回應物件并設定回應 cookie:
response = make_response(redirect(url_for('...')))
# Setting cookie similar to Flask Login way of setting its cookies
duration = current_app.config.get('REMEMBER_COOKIE_DURATION', COOKIE_DURATION)
secure = current_app.config.get('REMEMBER_COOKIE_SECURE', COOKIE_SECURE)
httponly = current_app.config.get('REMEMBER_COOKIE_HTTPONLY', COOKIE_HTTPONLY)
expires = duration datetime.utcnow()
# encode additional data to ensure that the user cannot simply use the value
# from the remember cookie
data = encode_cookie(str(session['_user_id']) '_cookie_variable')
response.set_cookie(
'cookie_variable',
value=data,
expires=expires,
secure=secure,
httponly=httponly
)
return response
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/372466.html
