User Session Management with Flask-Login
User Session Management with Flask-Login
Once a user verifies their credentials, an application must persist their authenticated state across subsequent requests without asking them to re-enter their password on every page click.
Flask-Login is the standard extension for managing user session lifecycles in Flask. It handles logging users in, logging them out, tracking active sessions via cookies, and protecting views with the @login_required decorator.
1. Installing and Configuring Flask-Login
Install the extension:
In app.py:
2. Implementing the UserMixin on Your User Model
Flask-Login requires your User model to implement four attributes/methods:
is_authenticated: ReturnsTrueif user is logged in.is_active: ReturnsTrueif user account is active and unbanned.is_anonymous: ReturnsFalsefor real users.get_id(): Returns a unique string identifying the user.
Instead of writing these manually, subclass flask_login.UserMixin:
3. The user_loader Callback
Flask-Login stores only the user's ID inside the encrypted session cookie. On each incoming request, Flask-Login invokes a callback function you register with @login_manager.user_loader to fetch the full User object from the database:
If the ID is invalid or user no longer exists, the callback must return None.
4. Authenticating Users (login_user, logout_user, current_user)
5. Protecting Routes with @login_required
To restrict access to authenticated members only, decorate the view function with @login_required:
In templates, current_user is globally accessible without explicitly passing it from Python:
Practice Quiz
@login_manager.user_loader callback function?remember=True in login_user(user, remember=True) do?Role-Based Access Control & Custom Decorators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Password Hashing with Werkzeug Security | Role-Based Access Control & Custom Decorators |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.