Flask-login: remember me not working if login_managers session_protection is set to strong

2024/10/5 11:26:38

i am using flask-login to integrate session management in my flask app. But the remember me functionality doesn't work if i set the session_protection to strong, however, it works absolutely fine if it's set to basic.

user_loader:

@login_manager.user_loader
def load_user(email):user = get_user_with_email(email)if user:return User(user.id, user.email, user.role_id, user.createtime, user.updatetime)

to fetch user from the database:

from psycopg2.extras import NamedTupleCursordef get_user_with_email(email):cursor = get_db().cursor(cursor_factory=NamedTupleCursor)cursor.execute('SELECT * FROM users WHERE email = %s', (email,))return cursor.fetchone()

and my user class:

class User(UserMixin):def __init__(self, username, email, role_id, createtime, updatetime):self.username = usernameself.email = emailself.role_id = role_idself.createtime = createtimeself.updatetime = updatetime@propertydef password(self):raise AttributeError('password is not a readable property')@password.setterdef password(self, password):self._password = generate_password_hash(password)def verify_password(self, password):return check_password_hash(self._password, password)@propertydef is_active(self):"""All users are active"""return True@propertydef is_anonymous(self):"""Always return False, anonymous users aren't supported"""return Falsedef get_id(self):"""Return username for flask_login to use it as user id"""return self.email@propertydef is_authenticated(self):"""All users are authenticated"""return Truedef register(self, password):self.password = password# Todo: complete the registration logicdef __repr__(self):return 'User(username={0}, email={1})'.format(self.username, self.email)

I am doing exactly what is mentioned in the documentation, but still the user logs out when the browser closes in case of strong protection. i am not sure what's going wrong.

I would appreciate any help, thanks !

Answer

You are not doing anything wrong, that is desired behavior when session protection is set to strong.

Edit:

Basically, when session protection is set (to basic or strong), after user logs in, session identifier is computed (based on users IP and users user-agent) and stored. And it is then computed upon each new request and checked with stored version.

After browser restart in order to load a user Flask-Login will check, beside the remember_me cookie, if the session id matches stored value. But since browser is restarted there won't be stored session id value and this test won't pass.So one of these two things will happen then.

  • If the protection is set to basic, session will be flagged as not fresh and user will be loaded from remember me cookie.

  • If the protection is set to strong the user won't be loaded and remember me cookie will be deleted.

It is good practice, if basic setting is used, to decorate view function that handles sensitive operations(such as password change) with fresh_login_required. As stated in the official docs:

flask_login.fresh_login_required(func)If you decorate a view with this, it will ensure that the current user’s login is fresh - i.e. their session was not restored from a ‘remember me’ cookie. Sensitive operations, like changing a password or e-mail, should be protected with this, to impede the efforts of cookie thieves.

https://flask-login.readthedocs.io/en/latest/_modules/flask_login/utils.html#fresh_login_required

https://en.xdnf.cn/q/70491.html

Related Q&A

Does any magic happen when I call `super(some_cls)`?

While investigating this question, I came across this strange behavior of single-argument super:Calling super(some_class).__init__() works inside of a method of some_class (or a subclass thereof), but …

How to get unpickling to work with iPython?

Im trying to load pickled objects in iPython.The error Im getting is:AttributeError: FakeModule object has no attribute WorldAnybody know how to get it to work, or at least a workaround for loading obj…

Basic questions about nested blockmodel in graph-tool

Very briefly, two-three basic questions about the minimize_nested_blockmodel_dl function in graph-tool library. Is there a way to figure out which vertex falls onto which block? In other words, to ext…

How to get multiple parameters with same name from a URL in Pylons?

So unfortunately I find myself in the situation where I need to modify an existing Pylons application to handle URLs that provide multiple parameters with the same name. Something like the following...…

Kivy: Access configuration values from any widget

Im using kivy to create a small App for computer aided learning.At the moment I have some problems with accessing config values. I get the value withself.language = self.config.get(basicsettings, langu…

Multiprocessing with threading?

when I trying to make my script multi-threading, Ive found out multiprocessing,I wonder if there is a way to make multiprocessing work with threading?cpu 1 -> 3 threads(worker A,B,C) cpu 2 -> 3 …

Pandas Groupby Unique Multiple Columns

I have a dataframe.import pandas as pd df = pd.DataFrame( {number: [0,0,0,1,1,2,2,2,2], id1: [100,100,100,300,400,700,700,800,700], id2: [100,100,200,500,600,700,800,900,1000]})id1 id2 nu…

OpenCV Error: Assertion failed when using COLOR_BGR2GRAY function

Im having a weird issue with opencv. I have no issues when working in a jupyter notebook but do when trying to run this Sublime.The error is: OpenCV Error: Assertion failed (depth == CV_8U || depth == …

matplotlib 1.3.1 has requirement numpy=1.5, but youll have numpy 1.8.0rc1 which is incompatible

Im executing bellow command in Mac (High Sierra) as a part of getting started with pyAudioAnalysis.pip install numpy matplotlib scipy sklearn hmmlearn simplejson eyed3 pydub Im getting following error…

VS Code Debugger Immediately Exits

I use VS Code for a python project but recently whenever I launch the debugger it immediately exits. The debug UI will pop up for half a second then disappear. I cant hit a breakpoint no matter where i…