flask-login session gets destroyed on every apache

2019-05-26 12:49发布

问题:

I am using flask-login https://github.com/maxcountryman/flask-login and the field remember in login_user does not seem to work.

The session gets destroyed after every restart of the apache ..ideally the remember field should take care of this.. even the session values gets destroyed. this is really frustrating... anyone knowing the solution please ping .. thanks i am using login_user as

login_user(user, remember=True)

回答1:

If anyone is suffering with this problem, you have to write the function user_loader properly.

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


回答2:

you have to set the get_auth_token in the user mixen as well as the user_loader

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)

And

@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

Both of those methods use the module itsdangerous to encrypt the remember me cookie

from itsdangerous import URLSafeTimedSerializer

I wrote a blog post about how I did it Flask-Login Auth Tokens



回答3:

I ran into this issue, but it was because we were setting Flask.secret_key to a new GUID on startup. We moved this to a configuration file (unique ID per environment) and now the session is persisted.