MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
User Session Management with Flask-Login0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
6.1Password Hashing with Werkzeug Security6.2User Session Management with Flask-Login6.3Role-Based Access Control & Custom Decorators
HomeTutorialsFlaskUser Session Management with Flask-Login
Role-Based Access Control & Custom Decorators

User Session Management with Flask-Login

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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:

1pip install flask-login

In app.py:

1from flask import Flask
2from flask_login import LoginManager
3 
4app = Flask(__name__)
5app.config["SECRET_KEY"] = "super-secret-session-key"
6 
7login_manager = LoginManager()
8login_manager.init_app(app)
9 
10# Specify the route endpoint where unauthenticated users should be redirected
11login_manager.login_view = "login"
12login_manager.login_message = "Please log in to access this page."
13login_manager.login_message_category = "warning"

2. Implementing the UserMixin on Your User Model

Flask-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:

1from flask_login import UserMixin
2from flask_sqlalchemy import SQLAlchemy
3 
4db = SQLAlchemy()
5 
6class User(UserMixin, db.Model):
7 __tablename__ = "users"
8
9 id = db.Column(db.Integer, primary_key=True)
10 username = db.Column(db.String(50), unique=True, nullable=False)
11 password_hash = db.Column(db.String(256), nullable=False)
12 role = db.Column(db.String(20), default="student")

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:

1@login_manager.user_loader
2def load_user(user_id):
3 # user_id is passed as a string by Flask-Login
4 return User.query.get(int(user_id))

If the ID is invalid or user no longer exists, the callback must return None.


4. Authenticating Users (login_user, logout_user, current_user)

1from flask import render_template, redirect, url_for, flash, request
2from flask_login import login_user, logout_user, login_required, current_user
3from werkzeug.security import check_password_hash
4from models import User
5 
6@app.route("/login", methods=["GET", "POST"])
7def login():
8 if current_user.is_authenticated:
9 return redirect(url_for("dashboard"))
10
11 if request.method == "POST":
12 username = request.form.get("username")
13 password = request.form.get("password")
14 remember = request.form.get("remember") == "on"
15
16 user = User.query.filter_by(username=username).first()
17 if user and check_password_hash(user.password_hash, password):
18 # Log the user into session
19 # remember=True issues a persistent 'remember me' cookie
20 login_user(user, remember=remember)
21 flash("Welcome back!", "success")
22
23 # Handle post-login redirection (e.g. ?next=/profile)
24 next_page = request.args.get("next")
25 return redirect(next_page or url_for("dashboard"))
26 else:
27 flash("Invalid username or password.", "danger")
28
29 return render_template("login.html")
30 
31@app.route("/logout")
32@login_required
33def logout():
34 logout_user()
35 flash("You have been signed out.", "info")
36 return redirect(url_for("home"))

5. Protecting Routes with @login_required

To restrict access to authenticated members only, decorate the view function with @login_required:

1@app.route("/dashboard")
2@login_required
3def dashboard():
4 # current_user is available everywhere!
5 return render_template("dashboard.html", user=current_user)

In templates, current_user is globally accessible without explicitly passing it from Python:

1{% if current_user.is_authenticated %}
2 <p>Logged in as: {{ current_user.username }}</p>
3 <a href="{{ url_for('logout') }}">Sign Out</a>
4{% else %}
5 <a href="{{ url_for('login') }}">Sign In</a>
6{% endif %}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What base class can be mixed into a User model to provide Flask-Login's required authentication properties automatically?
Question 2
What is the purpose of the @login_manager.user_loader callback function?
Question 3
What decorator prevents unauthenticated users from accessing a route in Flask-Login?
Question 4
How is the currently authenticated user accessed inside Jinja2 templates?
Question 5
What does setting remember=True in login_user(user, remember=True) do?
Next Lesson

Role-Based Access Control & Custom Decorators

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Password Hashing with Werkzeug SecurityRole-Based Access Control & Custom Decorators

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext