Resetting the expiration time for a cookie in Flask Resetting the expiration time for a cookie in Flask flask flask

Resetting the expiration time for a cookie in Flask


You can renew the session to the client at each request using a @before_request handler.

Try the following:

@app.before_requestdef func():  session.modified = True


Should be enough with:

from datetime import timedelta# User will be logout after this time of inactivityPERMANENT_SESSION_LIFETIME = timedelta(minutes=30)SESSION_REFRESH_EACH_REQUEST = True

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


  1. Get cookie token from request
    auth_token = request.cookies.get('jwt')
  1. Set token back in response cookie with max_age. As a result, max_age moves forward with each request activity. If there is no activity from the user side then cookie will expire on time.

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

I did it for myself as follows:

I already had a token_rquired_decorator on each API call. So I placed my logic there in the make_response function.

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

In make_response function. I am setting a cookie again that will eventually move my cookie expiry time forward with each request considering as activity.

 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

I hope it will help the community. Don't forget to appreciate it. thanks