python
48 lines · 9 steps
Session-based auth with a Flask Blueprint
A login_required decorator plus login and logout views build a complete session-based authentication flow in Flask.
Explained by
highlit
1from functools import wraps
2from flask import Blueprint, session, request, redirect, url_for, flash, render_template
3from werkzeug.security import check_password_hash
4
5from app.models import User
6
7auth = Blueprint("auth", __name__)
8
9
10def login_required(view):
11 @wraps(view)
12 def wrapped(*args, **kwargs):
13 if "user_id" not in session:
14 flash("Please sign in to continue.", "warning")
15 return redirect(url_for("auth.login", next=request.path))
16 return view(*args, **kwargs)
17
18 return wrapped
19
20
21@auth.route("/login", methods=["GET", "POST"])
22def login():
23 if request.method == "GET":
24 return render_template("auth/login.html")
25
26 email = request.form["email"].strip().lower()
27 password = request.form["password"]
28
29 user = User.query.filter_by(email=email).first()
30 if user is None or not check_password_hash(user.password_hash, password):
31 flash("Invalid email or password.", "error")
32 return render_template("auth/login.html", email=email), 401
33
34 session.clear()
35 session["user_id"] = user.id
36 session.permanent = bool(request.form.get("remember"))
37
38 next_url = request.args.get("next")
39 if next_url and next_url.startswith("/"):
40 return redirect(next_url)
41 return redirect(url_for("dashboard.index"))
42
43
44@auth.route("/logout", methods=["POST"])
45def logout():
46 session.clear()
47 flash("You have been signed out.", "info")
48 return redirect(url_for("auth.login"))
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing only a user id in the signed session keeps authentication state small and server-verifiable.
- 2A login_required decorator centralizes access control so individual views stay focused on their work.
- 3Validating a redirect target against a leading slash prevents open-redirect attacks after login.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
ruby
require "openssl" require "base32" class TOTP
How TOTP one-time codes work in Ruby
hmac
authentication
totp
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/session-based-auth-with-a-flask-blueprint-explained-python-30e7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.