【问题标题】:Resetting the expiration time for a cookie in Flask在 Flask 中重置 cookie 的过期时间
【发布时间】:2013-11-14 15:28:06
【问题描述】:

我正在使用 Python Web 框架 Flask。我在我的应用程序中使用会话。对于我的名为main 的应用程序,我设置了main.permanent_session_lifetime = timedelta(days=5),这样用户在登录后将保持登录状态5 天。但即使是活动用户也会在5 天后注销。我希望他们每次访问该网站时都重置过期时间,以便您仅在 不活动 5 天后退出。大多数网站都以这种方式工作。我如何使用 Flask 做到这一点?

【问题讨论】:

  • Flask 试图为您提供工具来自己编写类似的东西。您如何定义“活动”取决于网站。 “活动”是访问网站,还是购买产品?如您所见,不可能有诸如“不活动”之类的选项,您必须自己实现它。
  • 就我而言,活动只是意味着访问该站点。如果他们在 cookie 过期之前访问了网站上的任何页面,我希望从那时起将过期时间重置为 5 天。
  • 看看这个答案https://stackoverflow.com/a/49891626它对我有用。

标签: python session flask


【解决方案1】:

您可以使用@before_request 处理程序在每次请求时更新与客户端的会话。

尝试以下方法:

@app.before_request
def func():
  session.modified = True

【讨论】:

  • 效果很好。实际上,我之前因为其他原因想要 @app.before_request 功能,所以很高兴知道这一点。
  • 这在使用服务器端会话 (flask-kvsession) 时不起作用。任何想法如何解决它?
  • @zengr 这是 Flask-kvsession 的问题,因为它说是“Flask 的基于 cookie 签名的会话管理的替代品”。它没有完全完成它的工作。发布错误报告。一种解决方法可能是调用.regenerate() 方法。
  • 是的,我放弃了 flask-kvsession 并实现了这个:flask.pocoo.org/snippets/75
【解决方案2】:

应该足够了:

from datetime import timedelta

# User will be logout after this time of inactivity
PERMANENT_SESSION_LIFETIME = timedelta(minutes=30)
SESSION_REFRESH_EACH_REQUEST = True

https://flask.palletsprojects.com/en/1.1.x/config/

【讨论】:

  • 不需要将'SESSION_REFRESH_EACH_REQUEST'设置为True,因为它默认设置为True。
【解决方案3】:
  1. request获取cookie令牌
    auth_token = request.cookies.get('jwt')
  1. 使用max_age 将令牌设置回响应cookie。因此,max_age 会随着每个请求活动向前移动。如果用户端没有任何活动,则 cookie 将按时过期。

     response.set_cookie(key="jwt",
                        value=auth_token,
                        max_age=IN_SECONDS,
                        httponly=True,
                        samesite="Strict",
                        )
    

我为自己做了如下:

我已经在每个 API 调用上都有一个 token_rquired_decorator。所以我把我的逻辑放在make_response函数中。

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):

        # some_code here 
        _response, status_code = f(*args, **kwargs)
        return make_response(_response, auth_token, status_code)

    return decorated

make_response 函数中。我再次设置了一个 cookie,最终将我的 cookie 过期时间向前移动,每个请求都被视为活动。

 def make_response(_response: Dict[str, Any], auth_token: str, status_code: int):
    response = Response(
        json.dumps(_response).encode('utf-8'),
        status=status_code,
        mimetype="application/json"
    )
    response.set_cookie(key="jwt",
                        value=auth_token,
                        max_age=Config.COOKIE_MAX_AGE,
                        httponly=True,
                        samesite="Strict",
                        )
    return response

我希望它对社区有所帮助。不要忘记欣赏它。谢谢

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2012-05-19
    相关资源
    最近更新 更多