Flask Authorization and authentication Timing out the login session


Example

Its good practice to time out logged in session after specific time, you can achieve that with Flask-Login.

from flask import Flask, session
from datetime import timedelta
from flask_login import LoginManager, login_require, login_user, logout_user

# Create Flask application

app = Flask(__name__) 

# Define Flask-login configuration 

login_mgr = LoginManager(app)
login_mgr.login_view = 'login'
login_mgr.refresh_view = 'relogin'
login_mgr.needs_refresh_message = (u"Session timedout, please re-login")
login_mgr.needs_refresh_message_category = "info"


@app.before_request
def before_request():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)

Default session lifetime is 31 days, user need to specify the login refresh view in case of timeout.

app.permanent_session_lifetime = timedelta(minutes=5)

Above line will force user to re-login every 5 minutes.