Flask Flask-Login Extension
Flask-Login is an extension that manages user authentication for you. It handles session management, the "remember me" feature, protecting routes, and loading the current user — all with minimal code. It does not handle passwords or registration; it focuses purely on session-based login state.
Installing Flask-Login
pip install flask-loginSetting Up Flask-Login
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login' # redirect here if not logged in
login_manager.login_message_category = 'info'The UserMixin
Your User model must implement four methods: is_authenticated, is_active, is_anonymous, and get_id(). Flask-Login provides UserMixin which implements all four with sensible defaults:
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(256))
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)The User Loader
Flask-Login calls this function on every request to reload the user from the database using the ID stored in the session:
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))Logging In and Out
from flask_login import login_user, logout_user, login_required, current_user
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user = User.query.filter_by(email=request.form.get('email')).first()
if user and user.check_password(request.form.get('password')):
remember = 'remember' in request.form
login_user(user, remember=remember)
return redirect(url_for('dashboard'))
flash('Invalid credentials.', 'danger')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))login_user(user) stores the user's ID in the session. logout_user() clears it. The remember=True option sets a persistent cookie so the user stays logged in even after the browser closes.
Protecting Routes with @login_required
@app.route('/dashboard')
@login_required
def dashboard():
return render_template('dashboard.html', user=current_user)Flask-Login redirects unauthenticated users to login_manager.login_view (set earlier as 'login') with a flash message. After they log in, Flask-Login redirects them back to the page they originally requested.
current_user
current_user is a proxy object available in every view function and template. It represents the currently logged-in user, or an anonymous user object if nobody is logged in.
{# In any template #}
{% if current_user.is_authenticated %}
<p>Hello, {{ current_user.username }}!</p>
<a href="{{ url_for('logout') }}">Log Out</a>
{% else %}
<a href="{{ url_for('login') }}">Log In</a>
{% endif %}Custom Unauthorized Handler
Customize what happens when an unauthenticated user hits a protected route:
@login_manager.unauthorized_handler
def unauthorized():
flash('Please log in to access this page.', 'warning')
return redirect(url_for('login'))Fresh Login Check
For sensitive actions like changing a password, require the user to have logged in recently (not just from a remembered session):
from flask_login import fresh_login_required
@app.route('/change-password')
@fresh_login_required
def change_password():
return render_template('change_password.html')If the user is logged in via the "remember me" cookie but has not entered credentials this session, Flask-Login redirects them to log in again.
Flask-Login vs Manual Sessions
| Feature | Manual Session | Flask-Login |
|---|---|---|
| Session management | Write yourself | Handled automatically |
| current_user proxy | Look up in every route | Available everywhere |
| Remember Me | Manual cookie setup | One parameter: remember=True |
| Redirect after login | Manual | Automatic |
Summary
Flask-Login automates the session-management layer of authentication. Add UserMixin to your User model, register a user loader function, and use login_user(), logout_user(), and @login_required in your routes. The current_user proxy gives you the logged-in user in any view or template. Flask-Login handles the remember-me cookie, redirects after login, and anonymous user detection automatically.
