Problem
I need server-side sessions to expire after a given amount of time, but when using flask-sessions the session expiration is prolonged every time the site is refreshed.
What I have tried
I have set a lifetime on the sessions, but I can see that the expiry is determined on the client side, and that it is prolonged every time I refresh the site:
app.config['PERMANENT_SESSION'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(minutes=1)
I tried setting it to False which gives the same results.
app.config['PERMANENT_SESSION'] = False
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(minutes=1)
How to I ensure that it is the server that determines whether a session has run out? I don't what the user to be able to set up a script that just keeps a session going infinitely!
I simply ended up adding the session-creation-date to the session store, and then I check the duration between this date and the current date.
Related
I would like to have a Flask session where the session cookie expires after 2 weeks regardless of activity.
I can get this to work without CSRF by setting:
SESSION_REFRESH_EACH_REQUEST=False
but this doesn't work when I enable CSRF.
With CSRF, the CSRF token is updated in the session for each request which causes the session expiration to be reset.
It seems that the only way to make the session expire after 2 weeks is to do it yourself (e.g., store the login date in the session or user database and deleting the session when the login date is more than 2 weeks old).
This seems like a common requirement so just curious if I am missing something?
The only way is to store date somewhere and then every day check if it has been >= 2 weeks since the stored date
Our Django application has the following session management requirements.
Sessions expire when the user closes the browser.
Sessions expire after a period of inactivity.
Detect when a session expires due to inactivity and display appropriate message to the user.
Warn users of a impending session expiry a few minutes before the end of the inactivity period. Along with the warning, provide users an option to extend their session.
If user is working on a long business activity within the app that doesn't involve requests being sent to the server, the session must not timeout.
After reading the documentation, Django code and some blog posts related to this, I have come up with the following implementation approach.
Requirement 1
This requirement is easily implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.
Requirement 2
I have seen a few recommendations to use SESSION_COOKIE_AGE to set the session expiry period. But this method has the following problems.
The session always expires at the end of the SESSION_COOKIE_AGE even if the user is actively using the application. (This can be prevented by setting the session expiry to SESSION_COOKIE_AGE on every request using a custom middleware or by saving the session on every request by setting SESSION_SAVE_EVERY_REQUEST to true. But the next problem is unavoidable due to the use of SESSION_COOKIE_AGE.)
Due to the way cookies work, SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE are mutually exclusive i.e. the cookie either expires on browser close or at the specified expiry time. If SESSION_COOKIE_AGE is used and the user closes the browser before the cookie expires, the cookie is retained and reopening the browser will allow the user (or anyone else) into the system without being re-authenticated.
Django relies only on the cookie being present to determine if the session is active. It doesn't check the session expiry date stored with the session.
The following method could be used to implemented this requirement and to workaround the problems mentioned above.
Do not set SESSION_COOKIE_AGE.
Set the expiry date of the session to be 'current time + inactivity period' on every request.
Override process_request in SessionMiddleware and check for session expiry. Discard the session if it has expired.
Requirement 3
When we detect that the session has expired (in the custom SessionMiddleware above), set an attribute on the request to indicate session expiry. This attribute can be used to display an appropriate message to the user.
Requirement 4
Use JavaScript to detect user inactivity, provide the warning and also an option to extend the session. If the user wishes to extend, send a keep alive pulse to the server to extend the session.
Requirement 5
Use JavaScript to detect user activity (during the long business operation) and send keep alive pulses to the server to prevent session from expiring.
The above implementation approach seem very elaborate and I was wondering if there might a simpler method (especially for Requirement 2).
Any insights will be highly appreciated.
I am just pretty new to use Django.
I wanted to make session expire if logged user close browser or are in idle(inactivity timeout) for some amount of time. When I googled it to figure out, this SOF question came up first. Thanks to nice answer, I looked up resources to understand how middlewares works during request/response cycle in Django. It was very helpful.
I was about to apply custom middleware into my code following top answer in here. But I was still little bit suspicious because best answer in here was edited in 2011. I took more time to search little bit from recent search result and came up with simple way.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 10 # set just 10 seconds to test
SESSION_SAVE_EVERY_REQUEST = True
I didn't check other browsers but chrome.
A session expired when I closed a browser even if SESSION_COOKIE_AGE set.
Only when I was idle for more than 10 seconds, A session expired. Thanks to SESSION_SAVE_EVERY_REQUEST, whenever you occur new request, It saves the session and updates timeout to expire
To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True, Django will save the session to the database on every single request.
Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.
Similarly, the expires part of a session cookie is updated each time the session cookie is sent.
django manual 1.10
I just leave answer so that some people who is a kind of new in Django like me don't spend much time to find out solution as a way I did.
Here's an idea... Expire the session on browser close with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Then set a timestamp in the session on every request like so.
request.session['last_activity'] = datetime.now()
and add a middleware to detect if the session is expired. something like this should handle the whole process...
from datetime import datetime
from django.http import HttpResponseRedirect
class SessionExpiredMiddleware:
def process_request(request):
last_activity = request.session['last_activity']
now = datetime.now()
if (now - last_activity).minutes > 10:
# Do logout / expire session
# and then...
return HttpResponseRedirect("LOGIN_PAGE_URL")
if not request.is_ajax():
# don't set this for ajax requests or else your
# expired session checks will keep the session from
# expiring :)
request.session['last_activity'] = now
Then you just have to make some urls and views to return relevant data to the ajax calls regarding the session expiry.
when the user opts to "renew" the session, so to speak, all you have to do is set requeset.session['last_activity'] to the current time again
Obviously this code is only a start... but it should get you on the right path
django-session-security does just that...
... with an additional requirement: if the server doesn't respond or an attacker disconnected the internet connection: it should expire anyway.
Disclamer: I maintain this app. But I've been watching this thread for a very, very long time :)
One easy way to satisfy your second requirement would be to set SESSION_COOKIE_AGE value in settings.py to a suitable amount of seconds. For instance:
SESSION_COOKIE_AGE = 600 #10 minutes.
However, by only doing this the session will expire after 10 minutes whether or not the user exhibits some activity. To deal with this issue, expiration time can be automatically renewed (for another extra 10 minutes) every time the user performs any kind of request with the following sentence:
request.session.set_expiry(request.session.get_expiry_age())
also you can use
stackoverflow build in functions
SESSION_SAVE_EVERY_REQUEST = True
In the first request, you can set the session expiry as
self.request.session['access_key'] = access_key
self.request.session['access_token'] = access_token
self.request.session.set_expiry(set_age) #in seconds
And when using the access_key and token,
try:
key = self.request.session['access_key']
except KeyError:
age = self.request.session.get_expiry_age()
if age > set_age:
#redirect to login page
I'm using Django 3.2 and i recommend using the django-auto-logout package.
It allows active time and idle time session control.
In the template you can use variables together with Javascript.
I use flask session in my app. In one of my handler I set session value and no session set in other handlers. But I found that in every response there is a http header: Set Cookie exists. Why does that happen?
app = Flask(__name__)
app.secret_key = r"A0Zr98j/3yX R~XHH!jmN'LWX/,?RT"
#app.route('/auth/login', methods=['POST'])
#crossdomain(origin='*')
def authlogin():
user = User(username=username, registered_at=sqlnow())
user.accounts = [Account(provider='weibo', access_token=access_token, uid=uid)]
account = user.accounts[0]
session['user_id'] = account.user_id
return jsonify({
'status': 'success',
'data': {
'user_id': account.user_id,
'uid': account.uid
}
})
#app.route('/api/movies/<movie_type>')
def moviescoming(movie_type):
if movie_type == 'coming':
return getmovies(MOVIE_TYPE_PLAYING, offset, limit)
else:
return getmovies(MOVIE_TYPE_COMING, offset, limit)
app.run(host='0.0.0.0', debug=True)
Code shows here:
https://github.com/aisensiy/dianying/blob/master/index.py
The Short Answer:
This is by design, but a recent change in Flask allows you to change this behavior through use of the SESSION_REFRESH_EACH_REQUEST option. As of the posting of this answer, that option is not yet in a stable release of Flask.
The Long Answer
Let's back up and discuss how cookies are supposed to work to begin with:
Cookies as a Standard
RFC 6265 defines that a cookie should expire when the agent (the browser) declares the session closed (typically, when the browser is closed), unless there was provided some mechanism to tell the browser when the cookie should actually expire:
Unless the cookie's attributes indicate otherwise, the cookie [...]
expires at the end of the current session (as defined by the user
agent).
[...]
If a cookie has neither the Max-Age nor the Expires attribute, the
user agent will retain the cookie until "the current session is over"
(as defined by the user agent).
If the server wishes a cookie to survive an agent restart, they need to set an expiration. Note that the Expires attribute is typically preferred due to the fact that Internet Explorer has a history of poor support for max-age.
Creating Permanent Cookies
So, it's impossible to say that a cookie should be "permanent". When people talk about a "permanent" cookie, what they really are talking about is a cookie that survives a browser restart. There are two strategies that I know of for creating this "permanent" cookie:
Set the cookie's expiration to something that is good enough to be considered permanent (such as the year 9999).
Set the cookie's expiration to something relatively recent in the future (e.g., 31 days), but every time the cookie is used update the expiration again. For example, on January 1st we will set the cookie to expire on February 1st, but then when the user uses the cookie on January 2nd we are updating the cookie (by using Set-Cookie) to have it expire on February 2nd.
The first method requires the Set-Cookie header to only be set to the client once (unless the cookie contents need to change).
The second method would require the Set-Cookie header to be sent with every update so that the expiration is constantly "pushed off" as the user continues to use the service. Note that it also isn't really "permanent", as a user that does not use your site for over 31 days will have their cookie expire.
RFC 6265 does have a bit to say on defining the expiration date:
Although servers can set the expiration date for cookies to the
distant future, most user agents do not actually retain cookies for
multiple decades. Rather than choosing gratuitously long expiration
periods, servers SHOULD promote user privacy by selecting reasonable
cookie expiration periods based on the purpose of the cookie. For
example, a typical session identifier might reasonably be set to
expire in two weeks.
So, while it doesn't explicitly say whether or not to be constantly updating the expiration date, it does seem to say that using a far-future date should NOT be considered a good practice.
Flask's Implementation of "Permanent Cookies"
Flask uses the second method (constantly updating the cookie expiration with Set-Cookie) by design. By default, the expiration of the cookie will be 31 days in the future (configurable by PERMANENT_SESSION_LIFETIME). With every request, Flask will use another Set-Cookie to push the expiration out another 31 days (or whatever you set your permanent session lifetime value to). Therefore, the Set-Cookie on every request you see is expected, even if the session has not changed.
Recently, however, there has been a discussion in a pull request regarding using Set-Cookie only when the cookie changes. This resulted in a new feature that allows the user to change how this works. Flask will continue to work as it has, but the user can set a new SESSION_REFRESH_EACH_REQUEST option to False, which will cause the Set-Cookie header to only be sent when the cookie changes.
The new item is documented as:
this flag controls how permanent sessions are refresh [sic]. If set to
True (which is the default) then the cookie is refreshed each
request which automatically bumps the lifetime. If set to False a
set-cookie header is only sent if the session is modified. Non
permanent sessions are not affected by this.
This new option, together with the existing PERMANENT_SESSION_LIFETIME, allows Flask developers to better tune exactly how their "permanent" cookies will be set to expire.
As of this answer's posting date (December 24th, 2013), the SESSION_REFRESH_EACH_REQUEST option has not been part of any Flask release, and therefore users wishing to use it will need to wait for a future Flask release.
Our Django application has the following session management requirements.
Sessions expire when the user closes the browser.
Sessions expire after a period of inactivity.
Detect when a session expires due to inactivity and display appropriate message to the user.
Warn users of a impending session expiry a few minutes before the end of the inactivity period. Along with the warning, provide users an option to extend their session.
If user is working on a long business activity within the app that doesn't involve requests being sent to the server, the session must not timeout.
After reading the documentation, Django code and some blog posts related to this, I have come up with the following implementation approach.
Requirement 1
This requirement is easily implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.
Requirement 2
I have seen a few recommendations to use SESSION_COOKIE_AGE to set the session expiry period. But this method has the following problems.
The session always expires at the end of the SESSION_COOKIE_AGE even if the user is actively using the application. (This can be prevented by setting the session expiry to SESSION_COOKIE_AGE on every request using a custom middleware or by saving the session on every request by setting SESSION_SAVE_EVERY_REQUEST to true. But the next problem is unavoidable due to the use of SESSION_COOKIE_AGE.)
Due to the way cookies work, SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE are mutually exclusive i.e. the cookie either expires on browser close or at the specified expiry time. If SESSION_COOKIE_AGE is used and the user closes the browser before the cookie expires, the cookie is retained and reopening the browser will allow the user (or anyone else) into the system without being re-authenticated.
Django relies only on the cookie being present to determine if the session is active. It doesn't check the session expiry date stored with the session.
The following method could be used to implemented this requirement and to workaround the problems mentioned above.
Do not set SESSION_COOKIE_AGE.
Set the expiry date of the session to be 'current time + inactivity period' on every request.
Override process_request in SessionMiddleware and check for session expiry. Discard the session if it has expired.
Requirement 3
When we detect that the session has expired (in the custom SessionMiddleware above), set an attribute on the request to indicate session expiry. This attribute can be used to display an appropriate message to the user.
Requirement 4
Use JavaScript to detect user inactivity, provide the warning and also an option to extend the session. If the user wishes to extend, send a keep alive pulse to the server to extend the session.
Requirement 5
Use JavaScript to detect user activity (during the long business operation) and send keep alive pulses to the server to prevent session from expiring.
The above implementation approach seem very elaborate and I was wondering if there might a simpler method (especially for Requirement 2).
Any insights will be highly appreciated.
I am just pretty new to use Django.
I wanted to make session expire if logged user close browser or are in idle(inactivity timeout) for some amount of time. When I googled it to figure out, this SOF question came up first. Thanks to nice answer, I looked up resources to understand how middlewares works during request/response cycle in Django. It was very helpful.
I was about to apply custom middleware into my code following top answer in here. But I was still little bit suspicious because best answer in here was edited in 2011. I took more time to search little bit from recent search result and came up with simple way.
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 10 # set just 10 seconds to test
SESSION_SAVE_EVERY_REQUEST = True
I didn't check other browsers but chrome.
A session expired when I closed a browser even if SESSION_COOKIE_AGE set.
Only when I was idle for more than 10 seconds, A session expired. Thanks to SESSION_SAVE_EVERY_REQUEST, whenever you occur new request, It saves the session and updates timeout to expire
To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True, Django will save the session to the database on every single request.
Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.
Similarly, the expires part of a session cookie is updated each time the session cookie is sent.
django manual 1.10
I just leave answer so that some people who is a kind of new in Django like me don't spend much time to find out solution as a way I did.
Here's an idea... Expire the session on browser close with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Then set a timestamp in the session on every request like so.
request.session['last_activity'] = datetime.now()
and add a middleware to detect if the session is expired. something like this should handle the whole process...
from datetime import datetime
from django.http import HttpResponseRedirect
class SessionExpiredMiddleware:
def process_request(request):
last_activity = request.session['last_activity']
now = datetime.now()
if (now - last_activity).minutes > 10:
# Do logout / expire session
# and then...
return HttpResponseRedirect("LOGIN_PAGE_URL")
if not request.is_ajax():
# don't set this for ajax requests or else your
# expired session checks will keep the session from
# expiring :)
request.session['last_activity'] = now
Then you just have to make some urls and views to return relevant data to the ajax calls regarding the session expiry.
when the user opts to "renew" the session, so to speak, all you have to do is set requeset.session['last_activity'] to the current time again
Obviously this code is only a start... but it should get you on the right path
django-session-security does just that...
... with an additional requirement: if the server doesn't respond or an attacker disconnected the internet connection: it should expire anyway.
Disclamer: I maintain this app. But I've been watching this thread for a very, very long time :)
One easy way to satisfy your second requirement would be to set SESSION_COOKIE_AGE value in settings.py to a suitable amount of seconds. For instance:
SESSION_COOKIE_AGE = 600 #10 minutes.
However, by only doing this the session will expire after 10 minutes whether or not the user exhibits some activity. To deal with this issue, expiration time can be automatically renewed (for another extra 10 minutes) every time the user performs any kind of request with the following sentence:
request.session.set_expiry(request.session.get_expiry_age())
also you can use
stackoverflow build in functions
SESSION_SAVE_EVERY_REQUEST = True
In the first request, you can set the session expiry as
self.request.session['access_key'] = access_key
self.request.session['access_token'] = access_token
self.request.session.set_expiry(set_age) #in seconds
And when using the access_key and token,
try:
key = self.request.session['access_key']
except KeyError:
age = self.request.session.get_expiry_age()
if age > set_age:
#redirect to login page
I'm using Django 3.2 and i recommend using the django-auto-logout package.
It allows active time and idle time session control.
In the template you can use variables together with Javascript.
I'm working on a website that requires us to log a user out after N minutes of inactivity. Are there any best practices for this using Django?
Take a look at the session middleware and its settings. Specifically these two:
SESSION_COOKIE_AGE
Default: 1209600 (2 weeks, in seconds)
The age of session cookies, in
seconds.
SESSION_SAVE_EVERY_REQUEST
Default: False
Whether to save the session data on
every request. If this is False
(default), then the session data will
only be saved if it has been modified
-- that is, if any of its dictionary values have been assigned or deleted.
Setting a low SESSION_COOKIE_AGE and turning SESSION_SAVE_EVERY_REQUEST on should work to create "sliding" expiration.
Setting the session cookie age in the django session middleware just sets the expiry time in the set-cookie header passed back to the browser. It's only browser compliance with the expiry time that enforces the "log out".
Depending on your reasons for needing the idle log-out, you might not consider browser compliance with the expiry time good enough. In which case you'll need to extend the session middleware to do so.
For example you might store an expiry time in your session engine which you update with requests. Depending on the nature of traffic to your site, you may wish to only write back to the session object once in X seconds to avoid excessive db writes.
On "settings.py", for session expiry time, set SESSION_COOKIE_AGE which is 1209600 seconds(2 weeks) by default and for inactive logout, set "True" to SESSION_SAVE_EVERY_REQUEST which is "False" by default as shown below:
# "settings.py"
SESSION_COOKIE_AGE = 180 # 3 minutes. "1209600(2 weeks)" by default
SESSION_SAVE_EVERY_REQUEST = True # "False" by default
Try setting settings.SESSION_COOKIE_AGE to N * 60 seconds.
http://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-age