Python – Deletes session cookies in Flask and Flask-Login

Deletes session cookies in Flask and Flask-Login… here is a solution to the problem.

Deletes session cookies in Flask and Flask-Login

We have a customer requirement that users must authenticate for each session.

Session cookies should solve the problem (that’s what they’re intended to do), but Chrome, Firefox, and Safari will persistent These session cookies if the user selects “Reopen last tab on startup” in their browser options.

Our customers don’t like this and want us to expire the cookie as soon as possible, for example 30 minutes (the site is not suitable for long periods of use).

I can set a “remember” cookie via Flask-Login,

but the problem is that even though I did, Flask-Login was still setting the session cookie, which means that even if the permanent cookie expires, session 1 is retained and the user is still authenticated.

How can I disable session cookies completely in the first place?

Solution

The best thing to do is to handle this on the server side, because as you pointed out, you don’t have 100% control over the cookie behavior on the client side.

Essentially, you want to change the user_loader callback function to check the user’s events (last time they were seen or last logged in).

For example:

@lm.user_loader
def load_user(id):

user = User.query.get(id)

if not user:
        return None

minutes = 30

if user.last_seen < (datetime.utcnow() - timedelta(minutes=minutes)):
        # Session has timed out
        return None

return user

Related Problems and Solutions