flask-login 会话在每次 apache 重新启动时都会被破坏

问题描述 投票:0回答:3

我正在使用flask-login https://github.com/maxcountryman/flask-login并且login_user中的记住字段似乎不起作用。

每次重新启动 apache 后,会话都会被破坏。理想情况下,记住字段应该处理这个问题。甚至会话值也会被破坏。这真的很令人沮丧...任何知道解决方案的人请 ping ..谢谢 我正在使用 login_user 作为

login_user(user, remember=True)
python flask flask-login
3个回答
3
投票

如果有人遇到这个问题,你必须正确编写函数user_loader

@login_manager.user_loader
def load_user(id):
    return "get the user properly and create the usermixin object"

2
投票

我遇到了这个问题,但这是因为我们在启动时将

Flask.secret_key
设置为新的 GUID。我们将其移至配置文件(每个环境的唯一 ID),现在会话已保留。


1
投票

您必须在用户 mixen 以及 user_loader 中设置 get_auth_token

class User(UserMixin):
    def get_auth_token(self):
        """
        Encode a secure token for cookie
        """
        data = [str(self.id), self.password]
        return login_serializer.dumps(data)

还有

@login_manager.token_loader
def load_token(token):
    """
    Flask-Login token_loader callback. 
    The token_loader function asks this function to take the token that was 
    stored on the users computer process it to check if its valid and then 
    return a User Object if its valid or None if its not valid.
    """

    #The Token itself was generated by User.get_auth_token.  So it is up to 
    #us to known the format of the token data itself.  

    #The Token was encrypted using itsdangerous.URLSafeTimedSerializer which 
    #allows us to have a max_age on the token itself.  When the cookie is stored
    #on the users computer it also has a exipry date, but could be changed by
    #the user, so this feature allows us to enforce the exipry date of the token
    #server side and not rely on the users cookie to exipre. 
    max_age = app.config["REMEMBER_COOKIE_DURATION"].total_seconds()

    #Decrypt the Security Token, data = [username, hashpass]
    data = login_serializer.loads(token, max_age=max_age)

    #Find the User
    user = User.get(data[0])

    #Check Password and return user or None
    if user and data[1] == user.password:
        return user
    return None

这两种方法都使用itsdangerous模块来加密记住我的cookie

from itsdangerous import URLSafeTimedSerializer

我写了一篇关于我是如何做到的博客文章 Flask-登录身份验证令牌

© www.soinside.com 2019 - 2024. All rights reserved.