Does your Flask app have a login page, but you still manually check session on every route? Flask-Login handles that for you: just attach the login_required decorator to routes that need protection, unauthenticated users are automatically redirected to the login page, and you get a secure “remember me” feature out of the box. Use it as soon as your Flask app has session-based login (a traditional web app), not an API.
The problem: manually checking the session
The common approach: in every sensitive route, check session["user_id"] and redirect to the login page if the user is not logged in:
from flask import session, redirect, url_for@app.route("/dashboard")def dashboard(): if "user_id" not in session: # phai lap lai o MOI route return redirect(url_for("login")) ...
This style has three problems:
- Duplicated code on every route — an app with 20 pages repeats the exact same check 20 times.
- Forgetting just one route exposes an entire sensitive page.
- A hand-rolled “remember me” means generating your own tokens, expiring them yourself, and preventing forgery yourself — get it wrong and you have a security hole.
The solution: let Flask-Login handle it
Install in one line:
pip install flask-login
A complete example — login, route protection, remember me, logout:
from flask import Flask, request, redirect, url_for, render_template_stringfrom flask_login import ( LoginManager, UserMixin, login_user, logout_user, login_required, current_user,)from werkzeug.security import check_password_hash, generate_password_hashapp = Flask(__name__)app.config["SECRET_KEY"] = "doi-thanh-chuoi-bi-mat-cua-ban" # giu kin!login_manager = LoginManager(app)login_manager.login_view = "login" # route chuyen ve khi chua dang nhap# Du lieu gia lap cho vi du (thuc te doc tu database)USERS = {"linh": {"id": "1", "username": "linh", "password_hash": generate_password_hash("mat-khau-manh")}}class User(UserMixin): def __init__(self, id, username): self.id = id self.username = username@login_manager.user_loaderdef load_user(user_id): for u in USERS.values(): if u["id"] == user_id: return User(u["id"], u["username"]) return None@app.route("/login", methods=["GET", "POST"])def login(): if request.method == "POST": username = request.form["username"] user = USERS.get(username) if user and check_password_hash(user["password_hash"], request.form["password"]): login_user(User(user["id"], username), remember="remember" in request.form) return redirect(url_for("dashboard")) return "Sai ten dang nhap hoac mat khau", 401 return render_template_string(""" <form method="post"> <input name="username" placeholder="Ten dang nhap"> <input name="password" type="password" placeholder="Mat khau"> <label><input type="checkbox" name="remember"> Ghi nho toi</label> <button>Dang nhap</button> </form>""")@app.route("/dashboard")@login_requireddef dashboard(): return f"Chao {current_user.username}!"@app.route("/logout")@login_requireddef logout(): logout_user() return redirect(url_for("login"))if __name__ == "__main__": app.run(debug=True)
Why this is better:
LoginManager(app)manages the session for you;login_manager.login_view = "login"makes unauthenticated requests redirect to the login page automatically.- The
Userclass inheritsUserMixin, which providesis_authenticated,get_id(), and more — no hand-written boilerplate. @login_manager.user_loader: the function that loads the user from the id stored in the session, run on every request — no more readingsession["user_id"]yourself.login_user(user, remember=True): marks the login;remember=Truesets a signed remember cookie, so the user stays logged in even after closing the browser.current_user: access the current user directly in both views and templates.
Apply it to your project
Attach login_required to admin routes, the dashboard, and profile pages — exactly where you used to check the session manually. If you use the Application Factory, instantiate LoginManager() inside create_app() and call init_app(app). Keep SECRET_KEY in an environment variable (don’t hardcode it), and when deploying over HTTPS enable SESSION_COOKIE_SECURE so session cookies only travel over HTTPS.
Related posts
- Flask: Using the Application Factory (create_app) so your app is easy to test and easy to extend from day one
- Flask: Securing your API with JWT using flask-jwt-extended — access tokens + refresh tokens in 5 minutes (web apps use Flask-Login sessions, APIs use JWT)
- Flask: Managing config per environment (dev/staging/prod) — no more hardcoding SECRET_KEY
Frequently asked questions
Does Flask-Login store passwords in the session?
No. The session only stores the user id, and session contents are signed with SECRET_KEY so they can’t be forged. The user_loader function reloads user information from the database on every request. Never store a password (even hashed) in the session yourself.
How does “remember me” work, and is it safe?
When you call login_user(..., remember=True), Flask-Login sets an extra remember_token cookie containing the user id signed with SECRET_KEY, valid for 365 days by default (configurable via REMEMBER_COOKIE_DURATION). An attacker cannot forge a valid cookie without knowing SECRET_KEY — which is why SECRET_KEY must be long and secret.
When should I use Flask-Login, and when should I use flask-jwt-extended?
Traditional web apps (rendered templates, login forms) use Flask-Login with sessions. APIs for mobile/SPA clients use JWT with flask-jwt-extended. The two are not mutually exclusive, but don’t mix them within the same login flow.
What if I forget to add login_required to a route?
Flask-Login doesn’t protect anything by itself — a route without the decorator stays open. Review all sensitive routes after integrating it, or with Blueprints use before_request to check in one place.
Running multiple workers (gunicorn) — any session issues?
No, because Flask sessions are stored client-side (signed cookies) by default, not on the server. As long as every worker shares the same SECRET_KEY, a user authenticated by one worker is recognized by all.
References
- Flask-Login documentation — https://flask-login.readthedocs.io/en/latest/
