ozn*_*ozn 2 python flask flask-login
在搜索了 Python Flask-Login 后,我找到了利用 header/api-key 身份验证而不是默认的 cookie 身份验证的方法。 https://flask-login.readthedocs.io/en/latest/#disabling-session-cookie-for-apis
然而,在初始/请求中,Flask 仍然在会话中使用 cookie 进行响应。上述方法仅确保任何新请求(@login_required)都能够在没有 cookie 的情况下进行身份验证(并使用标头或我的实现所需的任何方法)。
有办法禁用它吗?或者我错过了什么。
找到办法了。创建并配置“CustomSessionInterface”。
app = Flask(__name__)
app.config.update(
DEBUG = True,
SECRET_KEY = 'secret_xxx'
)
@user_loaded_from_header.connect
def user_loaded_from_header(self, user=None):
g.login_via_header = True
class CustomSessionInterface(SecureCookieSessionInterface):
"""Disable default cookie generation."""
def should_set_cookie(self, *args, **kwargs):
return False
"""Prevent creating session from API requests."""
def save_session(self, *args, **kwargs):
if g.get('login_via_header'):
print("Custom session login via header")
return
return super(CustomSessionInterface, self).save_session(*args,
**kwargs)
app.session_interface = CustomSessionInterface()
login_manager = LoginManager()
login_manager.init_app(app)
Run Code Online (Sandbox Code Playgroud)
should_set_cookie() 应返回 False。