Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Session cookie in Flask & Flask-Login

We have a requirement from a client that users should have to authenticate every session.

A session cookie should do the trick (it's what they're meant for, after all) but Chrome, Firefox, and Safari will persist these session cookies if the user has selected "reopen last tabs on startup" in their browser options.

Our client does not like this and would prefer us just to expire the cookies really quickly, like 30 min (the site is not intended for prolonged use).

I'm able to set up "remember" cookies via Flask-Login, but the issue is that even when I do, Flask-Login is still setting a session cookie, meaning that even after the permanent cookie expires, the session one is retained and the user is still authenticated.

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

like image 679
kevlarr Avatar asked Nov 18 '25 11:11

kevlarr


1 Answers

Your best bet is to handle this on the server side, because as you've pointed out, you're not able to 100% control the cookie behaviour on the client side.

Essentially you want to change your user_loader callback function to check the user's activity (either when they were last seen or when they 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
like image 90
Matt Healy Avatar answered Nov 20 '25 02:11

Matt Healy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!