[Python][Flask] Flask-login session_protection

 Flask-login session_protection

To implement a login feature using Flask, Flask-login library is used. The following is the basic syntax to implement it.

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = 'strong'

In this post, LoginManager.session_protection will be explained.

Explanation

Flask-Login provides an option security setting called session_protection to help prevent session hijacking (a situation where someone steals another user's session ID and impersonates them.)

It has 3 different levels.

  • basic
  • strong
  • None

basic

login_manager.session_protection = 'basic'

  • Monitors the session for suspicious changes (like IP or user-agent changes).
  • If a change is detected, it logs a warning internally but does not end the session.
  • Good for low-risk applications or during development.
  • The user stays logged in.
  • You can log or track changes, but no interruption to the user experience.

strong

login_manager.session_protection = 'strong'

  • Tracks the same details (IP address, user-agent).
  • If something suspicious is detected, Flask-Login will:
    • Clear the session (logs the user out).
    • Force the user to log in again.
  • Best for higher-security apps (e.g., user data, admin panels, or account-sensitive services).
  • If the session looks like it was hijacked or moved between devices/networks, it is invalidated.
  • User must reauthenticate.

Comments