Flasklogin:请记住,如果登录管理器的会话保护设置为“strong”,我就不工作了

2024-09-29 21:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用flask登录在我的flask应用程序中集成会话管理。但如果我将会话保护设置为strong,则“记住我”功能不起作用,但是,如果将其设置为基本。在

用户加载程序:

@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)

从数据库获取用户:

^{pr2}$

以及我的用户类:

class User(UserMixin):
    def __init__(self, username, email, role_id, createtime, updatetime):
        self.username = username
        self.email = email
        self.role_id = role_id
        self.createtime = createtime
        self.updatetime = updatetime

    @property
    def password(self):
        raise AttributeError('password is not a readable property')

    @password.setter
    def password(self, password):
        self._password = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self._password, password)

    @property
    def is_active(self):
        """All users are active"""
        return True

    @property
    def is_anonymous(self):
        """Always return False, anonymous users aren't supported"""
        return False

    def get_id(self):
        """Return username for flask_login to use it as user id"""
        return self.email

    @property
    def is_authenticated(self):
        """All users are authenticated"""
        return True

    def register(self, password):
        self.password = password
        # Todo: complete the registration logic

    def __repr__(self):
        return 'User(username={0}, email={1})'.format(self.username, self.email)

我所做的正是文档中提到的,但是当浏览器关闭时,用户仍然会注销,以防受到strong的保护。我不知道出什么事了。在

谢谢你的帮助,谢谢!在


Tags: 用户selfidflaskreturnisemaildef
1条回答
网友
1楼 · 发布于 2024-09-29 21:21:23

您没有做错任何事情,这是会话保护设置为强时所期望的行为。在

编辑:

基本上,当会话保护设置为(基本或强)时,用户登录后,会计算会话标识符(基于用户IP和用户用户用户代理)并存储。然后对每个新请求进行计算,并使用存储的版本进行检查。在

重新启动浏览器以加载用户Flask登录后,将在remember\u me cookie旁边检查会话id是否与存储值匹配。但由于浏览器重新启动,将不会存储会话id值,而此测试也不会通过。所以这两件事中的一件会发生。在

  • 如果保护设置为基本,会话将被标记为not fresh,用户将从remember me cookie加载。

  • 如果保护设置为强,则不会加载用户,并且会删除“记住我”cookie。

如果使用基本设置,则最好将处理敏感操作(如密码更改)的视图函数装饰为需要新的登录名。如官方文件所述:

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

相关问题 更多 >

    热门问题