Flask-Login: How to force Firefox/Chrome to remove

2019-06-21 04:23发布

问题:

I have been trying to learn Flask, and along the way the Flask-Login extension. I can make basic authentication work as expected. The issue that has me stumped involves the "Show my windows and tabs from last time" setting in Firefox and the "Continue where I left off" setting in Chrome. All the research I have done on this site and elsewhere indicates that these settings should only work for open tabs. So if you are authenticated and then close the tab, and then close the browser, the browser should only restore the session-only cookies for tabs that were open when the browser closed. However with both Firefox and Chrome the session-only cookie is still active when the browser is started again and I navigate to the page that is marked as @login_required. I should also mention that I am passing False to the login_user remember argument like so: login_user(user, remember=False)

I have played around with the idea of fresh logins with the Flask-Login extension thinking that closing the tab before closing the browser would surely mark the session as stale, but it doesn't. I examine the value of login_fresh() which returns true if the login is fresh, and it still returns True.

I found out how to make the login expire after a given time using session.permanent = True and then setting app.permanent_session_lifetime = 'so many minutes/seconds', which works perfectly, but isn't what I want.

I can live with the fact that Firefox / Chrome will remember session cookies for tabs that are open, but what I don't understand is why they remember session cookies for my site even when the tab is closed before closing the browser. Is this the expected behavior? Is it reasonable to expect the session cookie to be removed for my site when I close the tab first then the browser?

回答1:

Is this the expected behavior? Is it reasonable to expect the session cookie to be removed for my site when I close the tab first then the browser?

Apparently yes, this is expected behaviour, and no you are not reasonable to expect such a thing. The behaviour you are seeing appears to be a deliberate design decision in the way the browsers implement "session restore" functionality.

  • See this Firefox bug from 2009 (eternalsession) Session restore can result in excessive session cookie lifespan that has many duplicates and no solution.
  • Or this Chromium bug from 2012 Session Cookies not cleared when Chrome processes closed with a status of WontFix

So, in short, I don't think there's anything you can do about this from the server side, no matter how awesome flask is :(



回答2:

What Day says is spot on and your expectations should be correct. Nevertheless, there may be a work-around.

You can use a permanent session with a short lifetime (PERMANENT_SESSION_LIFETIME) and refresh its lifetime on every request (SESSION_REFRESH_EACH_REQUEST).

I think this is a rather new configuration (0.10 IIRC).