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 flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 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.