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.
Install the extension:
In app.py:
UserMixin on Your User ModelFlask-Login requires your User model to implement four attributes/methods:
is_authenticated: Returns True if user is logged in.is_active: Returns True if user account is active and unbanned.is_anonymous: Returns False for real users.get_id(): Returns a unique string identifying the user.Instead of writing these manually, subclass flask_login.UserMixin:
user_loader CallbackFlask-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.
login_user, logout_user, current_user)@login_requiredTo 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:
@login_manager.user_loader callback function?remember=True in login_user(user, remember=True) do?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Password Hashing with Werkzeug Security | Role-Based Access Control & Custom Decorators |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.