在搜索了 Python Flask-Login 后,我找到了利用 header/api-key 身份验证而不是默认的 cookie 身份验证的方法。 https://flask-login.readthedocs.io/en/latest/#disabling-session-cookie-for-apis
但是,在初始/请求中,Flask 仍然在 session 中使用 cookie 进行响应。上述方法仅确保任何新请求 (@login_required) 都能够在没有 cookie 的情况下进行身份验证(并使用 header 或我的实现所需的任何方法)。
有办法禁用它吗?或者我错过了什么。
最佳答案
找到办法了。创建了“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)
should_set_cookie() 应返回 False。
关于python - 在 Python Flask-login 中禁用 session Cookie 生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162502/