Django session expires at browser close OR after t

2020-07-10 06:44发布

问题:

The Django documentation states:

You can control whether the session framework uses browser-length sessions vs. persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies -- cookies that expire as soon as the user closes his or her browser. Use this if you want people to have to log in every time they open a browser.

This setting is a global default and can be overwritten at a per-session level by explicitly calling the set_expiry() method of request.session as described above in using sessions in views.

So when I set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in my settings file, this indeed is what it does. This is good because I want a user's session to expire upon browser close. However, I also want a user's session to expire after, say, 15 minutes of inactivity. If I use set_expiry() mentioned above, the SESSION_EXPIRE_AT_BROWSER_CLOSE is overridden so if a user closes the browser and then re-opens the browser before the expiration, the session is still valid. Not what I want.

In addition, the documentation for set_expiry() says the sessions expires after the set amount of time of inactivity. That's actually not true. It expires no matter what, whether my user is clicking around on the site or not.

So to summarize, what I want to do is:

  1. Have my sessions configured that if the user closes the browser, the session automatically expires.
  2. Set a session expiration length that is updated with activity, i.e. if a user does something else on the site, the expiration is reset.

Thoughts/suggestions?

回答1:

As Jiaaro suggested in this answer you can use SESSION_EXPIRE_AT_BROWSER_CLOSE and set a timestamp on session at each request and add a custom Middleware to handle the inactivity.



回答2:

From docs https://docs.djangoproject.com/en/1.8/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions

Some browsers (Chrome, for example) provide settings that allow users to continue browsing sessions after closing and re-opening the browser. In some cases, this can interfere with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting and prevent sessions from expiring on browser close. Please be aware of this while testing Django applications which have the SESSION_EXPIRE_AT_BROWSER_CLOSE setting enabled.



回答3:

Sessions expire when the user closes the browser:

This requirement implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.

Reference

Sessions expire after a period of inactivity:

SESSION_COOKIE_AGE is the age of session cookies, in seconds.
Default: 1209600 (2 weeks, in seconds)

Reference

You should set these option on your setting/__init__.py