When a user ticks “Remember me”, Flask-Login restores the session from the remember-me cookie and marks that session as non-fresh. The @login_required decorator does not distinguish fresh from stale sessions, so anyone holding the cookie can reach the change-password page. The fix: attach @fresh_login_required to sensitive routes, point login_manager.refresh_view at a re-authentication page, then call confirm_login() after the user enters the correct password.
The Problem
Imagine a user logs in with remember=True and then closes the browser. The next day they open it again, and Flask-Login restores the session from the remember-me cookie, so they do not need to log in again — convenient, but this session is marked non-fresh. The problem is that @login_required accepts both kinds of sessions, so the change-password route below opens its door to anyone holding that session, including someone borrowing the computer or a cookie thief.
from flask_login import login_required@app.route("/doi-mat-khau")@login_requireddef doi_mat_khau(): # Ai dang dang nhap cung vao duoc, ke ca phien # khoi phuc tu cookie remember-me return "Form doi mat khau"
The Solution
It takes just three steps. First, configure refresh_view so Flask-Login knows where to send users when their session is stale. Second, change the decorator on the sensitive route to @fresh_login_required. Third, write a re-authentication route: check the password, call confirm_login() to mark the session as fresh, then send the user back to the page they were heading to via the next parameter.
from flask_login import LoginManagerlogin_manager = LoginManager(app)login_manager.login_view = "dang_nhap"login_manager.refresh_view = "xac_thuc_lai"login_manager.needs_refresh_message = ( "De bao ve tai khoan, vui long nhap lai mat khau.")
from flask_login import fresh_login_required@app.route("/doi-mat-khau")@fresh_login_requireddef doi_mat_khau(): return "Form doi mat khau"
from flask import redirect, request, url_forfrom flask_login import confirm_login, current_user, login_requiredfrom werkzeug.security import check_password_hash@app.route("/xac-thuc-lai", methods=["GET", "POST"])@login_requireddef xac_thuc_lai(): if request.method == "POST": if check_password_hash( current_user.password_hash, request.form["password"] ): confirm_login() return redirect( request.args.get("next") or url_for("trang_chu") ) return "Mat khau khong dung", 401 return "Nhap lai mat khau de tiep tuc"
When a non-fresh session hits this route, Flask-Login automatically redirects the user to refresh_view with a next parameter pointing back to the original page. After successful re-authentication, confirm_login() marks the session as fresh, so the user goes straight to their destination without being asked again. Note: changing a password should still ask for the current password inside the form — fresh_login_required is an extra layer of protection, not a replacement for that.
Apply It to Your Project
Review the routes in your app that change sensitive data: change password, change email, delete account, view or regenerate API keys, change payment method. Attach @fresh_login_required to exactly those routes; profile pages and content reading can stay on @login_required so users are not bothered. If you need a flexible decision inside a view, use login_fresh() to check whether the current session is fresh before letting the request through.
Related Posts
- Flask: Managing Login with Flask-Login — login_required and remember me in 5 Minutes
- Flask: Lock Down Session Cookies with a Strong SECRET_KEY, Secure, and SameSite in 5 Minutes
- Flask: Hash Passwords Securely with Werkzeug — Never Store Plaintext in 5 Minutes
Frequently Asked Questions
How is fresh_login_required different from login_required?
login_required only checks whether the user is logged in. fresh_login_required also checks whether the session is fresh: a session that just logged in with a password is fresh, while a session restored from a remember-me cookie is not. That way, sensitive routes stay open for users who just logged in, but block stale sessions.
How long does a fresh session last?
A session stays fresh until it is destroyed, usually when the user closes the browser. When they reopen it later, Flask-Login restores the user from the remember-me cookie and this new session is non-fresh, so the first time they touch a sensitive route they will be asked to re-authenticate.
What happens if I forget to set refresh_view?
Flask-Login has nowhere to send the user, so it returns a 401 Unauthorized error. Always set login_manager.refresh_view when using fresh_login_required, just as login_view goes with login_required.
Do I need to enable session protection in strong mode?
Not required. By default Flask-Login already enables session protection in basic mode: when the IP or user-agent changes suspiciously, the session is marked non-fresh and sensitive routes ask for re-authentication. Strong mode deletes the session entirely on any anomaly, but it can cause unwanted logouts when combined with remember-me.
💬 Have you tried this in your own project? If you hit an error or have a shorter way to do it, leave a comment below — I read them all and will add the best ideas to the post.
Sources
- Flask-Login documentation — Fresh Logins: https://flask-login.readthedocs.io/en/latest/#fresh-logins
- Flask-Login documentation — Session Protection: https://flask-login.readthedocs.io/en/latest/#session-protection
