Home > Mobile >  How does a flask server know the user closed the browser to clean up a session
How does a flask server know the user closed the browser to clean up a session

Time:10-26

I haven't been able to find any explicit information on how flask cleans up it's sessions on the server side. I have read that 'By default a session lasts as long as your browser is open', but from what I can tell this just means that the browser deletes the cookie when it closes. If I'm understanding correctly, this means that the server still maintains the session in it's cache. In flask I can set a timeout by making the session permanent and setting the permanent_session_lifetime variable, but what happens if I don't do this?. I have a hard time believing the session would just linger forever, but the session documentation here doesn't describe the default behavior.

CodePudding user response:

So I think I figured this out and I had a misunderstanding of how Flask default cookies work. From looking at the code for Flask, I don't see any kind of server side caching of cookies. After a little bit more reading it seems that default Flask cookies are entirely client side. The SecureCookieSessionInterface that Flask uses encodes and signs all of the information and sends it to the browser to be stored. This means that once the browser deletes it, it is gone forever. The permanent property and permanent_session_lifetime don't manage any kind of server side caching; They simply determine whether or not the response will tell the browser to keep the cookie and, if so, how long it should keep it. This makes the default flask cookie far less secure than I thought it was. For server side session cookies it looks like I can use Flask-Session

Another interesting aspect of the Flask cookie implementation seems to be that permanent_cookie_lifetime is still used to expire the cookie even if it isn't set to permanent. The cookie is signed with an expiration date that is sent with it, and that defaults to 31 days. If you keep your tab/browser open for more than 31 days, the cookie will still expire. I'm only about 80% certain on this last bit, so if anyone knows better feel free to correct me.

  • Related