User authentication is a fundamental feature of web applications that allows users to create accounts, log in, and access personalized content. Flask-Login is a Flask extension that simplifies the process of implementing user authentication in your web application. In this guide, we'll explore how to use Flask-Login to authenticate users, manage sessions, and secure routes. By following this guide, you'll have the knowledge and code to add user authentication to your Flask application.

Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and creating a directory structure. Here's a sample structure:


Step 2: Installing Flask-Login

Install Flask-Login using pip:

pip install Flask-Login

Step 3: Configuring Flask-Login

Configure Flask-Login in your Flask application. Here's an example of Python code:

from flask import Flask, render_template, redirect, url_for, request
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
app = Flask(__name)
app.secret_key = 'your_secret_key'
login_manager = LoginManager()
class User(UserMixin):
def __init__(self, id): = id
def load_user(user_id):
return User(user_id)
def home():
return 'Welcome to the home page. <a href="/login">Login</a>'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user = User(1)
return redirect(url_for('dashboard'))
return render_template('login.html')
def dashboard():
return render_template('dashboard.html',
def logout():
return 'Logged out successfully. <a href="/">Home</a>'
if __name__ == '__main__':

Step 4: Creating Login and Dashboard Templates

Create HTML templates for the login and dashboard pages. Here's an example of a login form:

<!-- templates/login.html -->
<!DOCTYPE html>
<form method="POST">
<label for="username">Username:</label>
<input type="text" name="username" required>
<label for="password">Password:</label>
<input type="password" name="password" required>
<button type="submit">Login</button>

And here's an example of a dashboard page:

<!-- templates/dashboard.html -->
<!DOCTYPE html>
<h1>Welcome, {{ name }}</h1>
<a href="/logout">Logout</a>


Flask-Login simplifies user authentication in Flask applications, allowing you to create login systems, protect routes, and manage user sessions. By following this guide, you've learned how to set up Flask-Login, create login and dashboard pages, and protect routes. You can now implement user authentication in your Flask application with ease.