简体   繁体   中英

flask-login invalidates session randomly after authentication

I'm using flask-login https://flask-login.readthedocs.io/en/latest for session management. The user first login in (login.html) the application and go to home.html. However, after the user has authenticated and click different links, it will kick out the session and go back to login page. This happens very randomly and I'm not sure what went wrong? It is using apache. It seems okay with localhost but having this issue in apache. Are there specific apache configurations need to pay attention?

Please advise how to fix this issue? Thanks so much!!

    class User(UserMixin):
       pass

    @login_manager.user_loader
    def load_user(user_id):
       print "load_user...." + user_id
       user = User()
       user.id = user_id
       return user

    @app.route("/login", methods=['POST'])
    def login():
        #login procedure
        curr_user = User()
        curr_user.id = LOGIN_USERNAME
        login_user(curr_user)
        return redirect(url_for('home'))

    @app.route("/")
    @app.route("/home")
    @login_required
    def home():
        return render_template('home.html')

The function for route / does not validate for user's session and just returns the template for login.

Either modify your loading() function

from flask import url_for

@app.route("/")
def loading():
    return redirect(url_for('.home'))

Or do validation whether user is logged in

from flask_login import current_user

@app.route("/")
def loading():
   if current_user.is_authenticated:
       return render_template('home.html')
   else:
       return render_template('login.html')

Or

Remove the loading() funtion and add the / route to home()

@app.route("/")
@app.route("/home")
@login_required
def home():
    return render_template('home.html')

This way when ever the route / or /home is requested, flask validates the login (as @login_required decorator is present). If not logged in, login_view defined for LoginManager will be rendered.

lm = LoginManager()
lm.init_app(flask_app)
lm.login_view = '/login'

I know this is an old post, but I found this answer which seems to have solved it for me: https://stackoverflow.com/a/57162593/5424359 Basically, you need to make sure you set app.secret_key to some secret key. A simple way to get a key is as follows.

>>>import os
>>>os.urandom(24)

Take that number and set app.secret_key to it. Make sure you don't have the app generating a key every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM